MisterCat
MisterCat

Reputation: 1641

AJAX Raw Javascript Basic

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 –

Upvotes: 2

Views: 239

Answers (1)

mohamedrias
mohamedrias

Reputation: 18576

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.

Upvotes: 1

Related Questions