Understanding AJAX
AJAX enables the content to be loaded asynchronously from Server. This way the complete page can be small & fast; rest of content can be loaded when needed
AJAX, or Asynchronous JavaScript And XML, is the most commonly used term in Web Development.
For those who are aware of AJAX, it's not a problem; but for those who are beginners of web development face the problem in understanding and working with the AJAX.
Asynchronous JavaScript and XML (AJAX) is a set of things working together to achieve a rich internet browsing experience. AJAX does so by enabling the developer to load the page sections asynchronously from the server without making user to wait for the page to be loaded completely.
Asynchronous means doing the operation in background without making the user to wait for the operation to get completed.
So now how this request in known and how it works we will see.
First step is to create request and then send it to the server. So an XMLHttpRequest or ActiveXObject has to be created for this.
var xhr = false;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xhr =new XMLHttpRequest();
} else {// code for IE6, IE5
xhr =new ActiveXObject("Microsoft.XMLHTTP");
}
Above was the creation. Now it has to be sent. It can be sent as a GET or POST request. Basically for sending the request two methods are used open and send For GET request:
xhr.open("GET","callback.php?data=datavalue",true);
xhr.send();
For POST request the request header must be set as application/x-www-form-urlencoded
. So:
xhr.open("POST","callback.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("data=datavalue");
Now as the request is sent; we will wait for the response and check whether the request is completed and with proper response.
So for this, we can attach an event handler on onreaystatechange
, which will be triggered every time when there is a change in the ready state readyState
.
The following can be the possible values of the readyState
0 | UNINITIALIZED | The object has been created, but not initialized (the open method has not been called). |
1 | LOADING | The object has been created, but the send method has not been called. |
2 | LOADED | The send method has been called, but the status and headers are not yet available. |
3 | INTERACTIVE | Some data has been received. Calling the responseBody and responseText properties at this state to obtain partial results will return an error, because status and response headers are not fully available. |
4 | COMPLETED | All the data has been received, and the complete data is available in the responseBody and responseText properties. |
Now along with that we can handle the responses received from the sever. To handle the response status property of the XMLHttpRequest
(xhr
) object is used. Some of the HTTP status codes are as follows:
A full info on HTTP status codes can be found on following URLs:
Code | Code Description |
---|---|
200 | The request is OK (this is the standard response for successful HTTP requests) |
400 | The request cannot be fulfilled due to bad syntax |
404 | The requested page could not be found but may be available again in the future |
500 | A generic error message, given when no more specific message is suitable |
502 | The server was acting as a gateway or proxy and received an invalid response from the upstream server |
https://www.w3schools.com/tags/ref_httpmessages.asp
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
https://httpstatus.es/ https://www.restapitutorial.com/httpstatuscodes.html
And depending upon the combinations of the readyState and status we can handle the AJAX response properly. Moreover you can use the statusText property to check what status text has been returned from server.
So the readyState
as 4 and the status
as 200 (means statusText
as OK
) tells us that the request is complete and the proper response is available. Same can be written in terms of the code as follows:
xhr.onreadystatechange = function() {
if (4 === xhr.readyState && 200 == xhr.status) {
//code to handle response and DOM manipulation
}
}
or we we can write as stop processing if the readyState
is not 4
or status
is not 200
xhr.onreadystatechange = function() {
if (4 !== xhr.readyState || 200 !== xhr.status) {
// do not precess if request is not complete
return;
}
}
Now the response is contained by the responseText or responseXML property of XMLHttpRequest object. So if response is returned as XML; you can use responseXML property to use it and if response is returned as HTML string or JSON string then you can use the responseText property. For JSON you need to eval the text returned.
Let's consider XML response. Following is the XML received from the server (server will also has to return Content-Type as “text/xml“)
<?xml version="1.0" encoding="ISO-8859-1"?>
<USERS>
<USER>
<NAME>Pankaj Patel</NAME>
<URL>http://pankaj.pro</URL>
</USER>
<USER>
<NAME>Time to Hack</NAME>
<URL>https://time2hack.com</URL>
</USER>
</USERS>
And to handle above response following is the code
xhr.onreadystatechange = function() {
if (4 !== xhr.readyState || 200 !== xhr.status) {
// do not precess if request is not complete
return;
}
if (null !== xhr.responseXML) {
// handle XML response
xml = xhr.responseXML;
txt = "<table>";
names = xml.getElementsByTagName("NAME");
urls = xml.getElementsByTagName("URL");
for ( i=0; i < names.length; i++ ) {
txt += "<tr>";
txt += "<td>" + names[i].childNodes[0].nodeValue + "</td>";
txt += "<td>" + urls[i].childNodes[0].nodeValue + "</td>";
txt += "</tr>";
}
txt += "</table>";
document.getElementById('targetDiv').innerHTML = txt;
return;
}
}
And if the response is received as plain text then we can us the responseText property. For example in place of sending the XML; server send the already crafted table html as plain text then it can be handled as below:
xhr.onreadystatechange = function() {
if (4 !== xhr.readyState || 200 !== xhr.status) {
// do not precess if request is not complete
return;
}
if (null !== xhr.responseText) {
// handle non-XML response
document.getElementById('targetDiv').innerHTML = xhr.responseText;
return;
}
}
So now on combining all the above codes and cases the final code will look like this
var xhr = false;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xhr =new XMLHttpRequest();
} else {
// code for IE6, IE5
xhr =new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("POST","callback.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("data=datavalue");
xhr.onreadystatechange = function() {
if (4 !== xhr.readyState || 200 !== xhr.status) {
// do not precess if request is not complete
return;
}
if (null !== xhr.responseXML) {
// handle XML response
xml = xhr.responseXML;
txt = "<table>";
names = xml.getElementsByTagName("NAME");
urls = xml.getElementsByTagName("URL");
for (var i=0; i < names.length; i++) {
txt += "<tr>";
txt += "<td>" + names[i].childNodes[0].nodeValue + "</td>";
txt += "<td>" + urls[i].childNodes[0].nodeValue + "</td>";
txt += "</tr>";
}
txt += "</table>";
document.getElementById('targetDiv').innerHTML = txt;
return;
}
if (null === xhr.responseText) {
// handle non-XML response
document.getElementById('targetDiv').innerHTML = xhr.responseText;
return;
}
document.getElementById('targetDiv').innerHTML = 'The AJAX request returned a NULL response';
}
I have tried to cover the vey basics for AJAX and I hope I did it but if you need very detailed study on the XMLHttpRequest then go through https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest.
More suggestions and corrections are welcome.