









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
AJAX IN WEB TECHNOLOGY [COMPLETELY]....
Typology: Study notes
1 / 15
This page cannot be seen from the preview
Don't miss anything!










● AJAX stands for Asynchronous JavaScript And XML.
● It is used to create fast and dynamic webpages.
● It provides the facility to update parts of a web page, without reloading the whole page.
● It is not used independently, but it works with javascript, XHTML and CSS and XML.
● Its applications are browser and platform independent.
Applications using Ajax
● Google search engine.
● Google Maps.
● Gmail.
● YouTube.
● Facebook tabs.
Advantages of Ajax
● Ajax helps to improve user interaction with application.
● Ajax allows data buffering, which increases the speed of the application and reduces the wait time for the user.
● Refreshing the page is not necessary in Ajax which improves the bandwidth of an application.
● Dynamic filtering is possible using Ajax.
● Ajax supports execution of long-time queries.
Drawbacks
● The web page cannot connect with the browser history engine, if the data and format is not specific.
● It is necessary to test Ajax-JavaScript based applications to be tested on different browsers.
Step1: We need to write code in the browser using JavaScript. Step2: Create the XML HttpRequest object to communicate with the server without refreshing the page.
Step3: The JavaScript code in the browser reads, processes and updates, the data which comes back from the server which is XML or plain text.
Creating XMLHttpRequest Object
Syntax: variable = new XMLHttpRequest ( );
Example: Create XMLHttpRequest Object
var Xhttp; if(window.XMLHttpRequest ) { Xhttp = new XMLHttpRequest (); } else { xhttp = new ActivxObject (“Microsoft.XMLHTTP” ); }
Sending a request to a Server
To send a request to a server, we can use the open() and send () methods.
Syntax
xHttp.open (“GET”, “ajax_info.txt”, true); xhttp( );
Server Response
● To get the response from a server, we can use the responseText or responseXML property of the XMLHttp request.
● Server responseText property: We can use this property, if the response from the server is in plain text.
● Server responseXML Text Property: We can use this property, if the response from server is XML.
AJAX is not used independently, but it works with javascript, XHTML, CSS and XML.
● When a request is sent to server, we have to perform some action based on the response.
● We can use JavaScript function as an event.
AJAX - The XMLHttpRequest Object
The XMLHttpRequest object can be used to exchange data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
1. Create an XMLHttpRequest Object
All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable = new XMLHttpRequest();
2. Define a Callback Function
A callback function is a function passed as a parameter to another function.The callback function should contain the code to execute when the response is ready.
xhttp.onload = function() { // What to do when the response is ready }
3. Send a Request
To send a request to a server, you can use the open() and send() methods of the XMLHttpRequest object:
Example
// Create an XMLHttpRequest object const xhttp = new XMLHttpRequest();
// Define a callback function xhttp.onload = function() { // Here you can use the Data }
// Send a request xhttp.open("GET", "ajax_info.txt"); xhttp.send();
XMLHttpRequest Object Metho
XMLHttpRequest Object Properties
Property Description
onload Defines a function to be called when the request is received (loaded)
onreadystatechange Defines a function to be called when the readyState property changes
Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
open( method, url, async, user, psw )
Specifies the request
method : the request type GET or POST url : the file location async : true (asynchronous) or false (synchronous) user : optional user name psw : optional password
send() Sends the request to the server Used for GET requests
send( string ) Sends the request to the server. Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent
The onreadystatechange property defines a callback function to be executed when the readyState changes.
The status property and the statusText properties hold the status of the XMLHttpRequest object.
The onreadystatechange function is called every time the readyState changes.
When readyState is 4 and status is 200, the response is ready:
Example
function loadDoc() { const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "ajax_info.txt"); xhttp.send(); }
The onreadystatechange event is triggered four times (1-4), one time for each change in the readyState.
2: request received 3: processing request 4: request finished and response is ready
status 200: "OK" 403: "Forbidden" 404: "Page not found"
statusText Returns the status-text (e.g. "OK" or "Not Found")
AJAX stands for Asynchronous Javascript and XML.
It is a simple coding technique that allows Javascript code to make HTTP requests but gives rise to an important architectural style for building web applications. AJAX allows the developer to break the normal cycle of web behaviour where each action results in the delivery of a whole HTML page. Instead, an AJAX request can be made to return just enough data to update the current page to a new state. This changes the web from a page based application to one where a user interface presented in a web browser carries out transactions on a remote server. As such, AJAX has made a significant difference to the way that web applications are written and to the user experience of the web.
AJAX refers to two main technologies: Javascript and XML.
Javascript is the scripting language implemented in the browser that is used to make requests and update the page being viewed.
XML is the language used to exchange data between the server and the browser client. However, AJAX techniques can be used with other data formats and it is now much more common to use JSON for data interchange than XML. The AJAX acronym is so well known now that changing it to AJAJ is unlikely even if it better reflects current practice.
The other keyword in AJAX is Asynchronous which means that the requests that are sent by Javascript do not block the further execution of the script. The request is sent and is executed in the background. When the response is returned by the server, the system calls a function that has been registered as a callback at the time of the request. The callback function handles the response and updates the page. This asynchronous behaviour means that the main script can continue to process user interaction while the request is in progress, meaning that the application always feels like it is 'live' to the user.
A common web transaction is submitting a form to update some piece of information presented in a page. For example, adding a new message to a conversation in a forum. In the regular web context, the HTML page is delivered containing the current conversation and a form to submit a new message. The user enters the message and submits the form. The server stores the new message and returns a new page with all of the old messages plus this new one. Clearly there is redundancy here since the old messages are sent multiple times to the client. Using AJAX, the form is submitted via a Javascript request, the response comes back as a JSON (or XML) and is inserted into the current page. The old messages don't need to be re-sent and so the response appears much faster and less network bandwidth is used.
This change makes web applications much more similar to desktop applications in the way that they update the display and transfer information. It allows web applications to be more responsive and to continue to react to user input due to the asynchronous nature of the request. This has allowed the web to be used as a platform for developing versions of traditional desktop applications such as mail readers, word processors and spreadsheets. The web has become a cross-platform implementation option for developing sophisticated applications.
catch (e) {
try {
let httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
} return httpRequest;
}
This function creates a new request object and returns it. Our script can then use this request object by providing a URL, a payload (for a POST request) and a callback function. The callback function will be called when the request returns and will be passed the response that comes back. Here is an example callback function:
httpRequest.onreadystatechange = function () {
if ( this .readyState === 4) {
if ( this .status === 200) { text = this .responseText;
alert( this );
}
}
}
This callback function just pops up an alert box with the text returned from the request. The request object is accessed via the Javascript this variable - the callback function is actually a method of the request object and this refers to the current instance as it does in Java or C++.
The first thing the function does is to check the this.readyState which is used to indicate the status of the request. A value of 4 means that the request is complete (other values tell you that the request is in different stages of progress); this indicates that this callback function might be called before things are really done so we first check that all is well and only then try to process the result.
We then check this.status to make sure that the request succeeded. This means that we don't want to do anything if we got a 404 or other error response - although we could carry out a different action in this case. this.responseText is the verbatim content of the response that the server sends back. This sample callback function uses this to create an alert box.
The details of what will happen when the request has returned are now set up but we've not yet made the request. To do that we need to set the URL and request method and then invoke the request. Here's an example of how to do that:
httpRequest.open('GET', '/likes');
httpRequest.send(null);
Only when the send method is called is the request actually made. The main Javascript thread then continues (to handle any other user input) and the callback function will be called when the response returns.
Here is a summary of the properties of the XMLHttpRequest object including a few that we've not yet mentioned.
Property Description
onreadystatechang e
Reference to an event handler function/method that is called on every state change in the request.
readyState The (interactive) 4 (complete)^ state^ of^ the^ object:^0 (uninitialized)^1 (loading)^2 (loaded)^3
responseText the response as a string
responseXML
the response as an XML DOM object or null if the response was not XML
status The response status code (eg. 200)
statusText The response status text (eg. "OK")
XML and JSON Data
Two properties of the XMLHttpRequest object may contain data:
responseXML stores a DOM structured object of any XML data;
responseText stores the data as one complete string. As an example of handling XML data, assume that the response is an XML document containing the following:
Bob Bobalooba
The Boogaloo
The responseXML property of the response is a standard DOM object so we can use the DOM methods to access the data. Here's example code to get the name value from this document:
$.get({
url: '/likes',
success: { function (data) {
console.log(data.name)
console.log(data.dance)
}}
})
The $.get function implements the common case of sending a GET request and takes an object parameter that has properties defining the URL to request and a function to call when the request returns. This success function is called with the data that was returned and if this data was in JSON format, we can immediately make use of it (if the data was XML we can also handle it in a similar way to the example above).
jQuery also provides a $.post function to make a POST request or the more general $.ajax function that can send any kind of request with the appropriate configuration. For example, to send a POST request with two form variables:
$.post({
url: '/comment',
data: {
'user': 'Steve',
'message': 'Hello World!'
},
success: function (data) {
console.log("post succeeded")
}
})
To give a more complete example, consider an application that wants to have users register interest in something, so it includes the following form in the page:
Rather than have the form submitted in the normal way, which would result in a page reload, the application will intercept the submit event and submit the form data via an AJAX POST request. When the request returns, the page will be updated with a message that is in the response.
The following code uses jQuery to bind to the submit event. In the event handler we first get the values of the input fields in the form, then construct a POST request using jQuery. The data in the request is built from the form inputs. The success handler for the request is a function which receives the response and updates the page - in this case assuming that the server returns a JSON data structure containing a message to be displayed to the user.
$(document).ready( function (){
/* bind to the submit event on the form */
$('#registerform').submit( function (event){
/* get the form input values */
let name = $( this ).children("input[name='name']").val()
let email = $( this ).children("input[name='email']").val()
/* send a post request */
$.post({
url: 'http://example.org/register', /* target of POST request */
data: {
name: name,
email: email
},
success: function (data) {
/* assume data in response is a message to show the user */ $("#usermessage").innerHTML = data.message;
}
})
/* prevent the normal submission of the form */
event.preventDefault()
})