user1828505
user1828505

Reputation:

What happens during an Ajax call?

can you guys tell me whats happing behind the browser in ajax... i just know without refreshing a page all the data are loaded....

here is my code

<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>

Upvotes: 3

Views: 4537

Answers (1)

Levi Botelho
Levi Botelho

Reputation: 25234

When you make an AJAX request, your browser sends an HTTP request to a given address. The server on the other end of the request responds, and returns the data to your browser. This is the same thing that happens when you navigate to a new web page.

What makes AJAX different is that instead of navigating to the new page and displaying it outright, it takes the response data and envelops it in a JavaScript variable. This variable can then be manipulated with JavaScript and inserted into your page dynamically.

That is about it! The only thing that might remain somewhat of a mystery for you will be this line:

xmlhttp.onreadystatechange=function()

What this does is attach an event to the xmlhttp object, which actually executes the request. The event fires each time the "ready state" of the object changes. The "ready state" is kind of a status indicator for the state of the request. AJAX requests generally go through five stages:

  • UNSENT (0)
  • OPENED (1)
  • HEADERS_RECEIVED (2)
  • LOADING (3)
  • DONE (4)

Your data is not usable until the request has hit the "DONE" stage. By checking for the ready state code 4, you are effectively checking that the request has completed. Note that in some browsers you can also check the state using the constants that are defined above but because the constants are not defined universally across all browsers (Opera is a notable exception), it is best to stick with checking the numeric codes nonetheless.

It is also worth mentioning that not all the ready states are necessarily accessible from all browsers. Code 4 is pretty much a safe bet, but some of the earlier codes are not always implemented. This article goes into a bit more depth on the subject: http://www.ibm.com/developerworks/web/library/wa-ajaxintro3/.

The other thing you check along with the ready state code is the HTTP status code. You check to see that it equals 200 because a code of 200 means that the request executed normally. Other codes will be returned to you when the request completes unsuccessfully. A list of HTTP codes can be found here http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.

Upvotes: 6

Related Questions