Search code examples
javascriptajaxasynchronousxmlhttprequest

parameter "true" in xmlHttpRequest .open() method


From the reference I read in MDN, it says

If TRUE (the default), the execution of the JavaScript function will continue while the response of the server has not yet arrived.

This is the A in AJAX.

I have been using AJAX but then I was a little confused when I read that. I think the problem may be that I am not understanding AJAX concept clearly. I know of course AJAX does not refresh the page which means the connection to the server and the response are completely done in the background.

But what I can imagine happening according to that reference is that if I have a code like this in my JavaScript:

//true, therefore process the function while server retrieves url
var xmlResponse;
var url = "http://example.com/file.xml";
xml_req.open("GET", url, true); 

xml_req.onreadystatechange = function() {
     if(xml_req.readyState == 4 && xml_req.status == 200) {
        if(xml_req.responseText != null)
             xmlResponse = xml_req.responseXML; //server response may not yet arrive
        else {
             alert("failed");
             return false;
        }
     };
xml_req.send(null);

Doesn't that mean xmlResponse could be undefined in the sense that the server is still retrieving the data? Could somebody explain what really is the flow of the execution in AJAX technology? Thanks in advance.


Solution

  • I wrote a more detailed article here, but this is the basic idea.

    Setting it to true means you are making an asynchronous request. That means the code does not pause until the http request is complete. A synchronous call locks up the browser so nothing else runs. That can cause problems, so people prefer asynchronous.

    The XHR object updates us on what it is doing. It gives us the updates with the onreadystatechange event. We register a function with it so we can keep track of its status. The onreadystatechange gets called 4 times. Each with a different state

    0 = uninitialized
    1 = loading
    2 = loaded
    3 = interactive
    4 = complete
    

    The data is available to us when the readystate is 4.

    Now in the code you posted, it is checking for the complete state and it makes sure that the status is 200 [ok]

    if(xml_req.readyState == 4 && xml_req.status == 200){
    

    The value for xmlResponse will be undefined if you try to use it somewhere else in the code before it is returned. An example

    ml_req.send(null);
    alert(xmlResponse );
    

    One of the very first articles on the XMLHttpRequest article might be a good read for you. Apple Article on xmlhttpreq