2

i wonder why the open and send method when we using ajax comes at the end. Not before the responseText method

function loadXMLDoc()
{
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","xmlhttp_info.txt",true);
xmlhttp.send();
}

i'm a bit confused with the open method which take the url of our data/file. And how could the xmlhttp.responsetext method now which file we're working with, since the code is at the bottom –

2
  • Because you need to build the call and set the event handlers, once you have everything setup you can make the call.... Commented Mar 28, 2015 at 15:14
  • Note that open can be called before declaring the onreadystatechange callback. It's only the send method that sets the whole thing in motion (and then it's important that the XHR is ready for anything). Commented Mar 28, 2015 at 15:20

1 Answer 1

1

Basically we need to construct the request at first and bind necessary event handlers to process the response. Only then we need to fire the request. That's the reason why it's at the end.

if we fire the request at first, then we might not have any event handlers registered to handle the response.

So that's the reason why at first we are constructing the XHR object and binding the event hanlders using xmlhttp.onreadystatechange.

Sign up to request clarification or add additional context in comments.

2 Comments

i just a bit confused with the open method which take the url of our data/file. And how could the xmlhttp.responsetext method now which file we're working with, since the code is at the bottom
Once the request is triggered, the request details will be available in the xmlhttp object. And inside the event handler, The responseText will contain data from the response object which you might have got from the server. It has nothing to do with the request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.