javascriptajaxonreadystatechange

Why can't separate the function for xmlHttp.onreadystatechange?


The below js file test.js` works fine in my html.

function sendData()
{
    var formData = new FormData( document.querySelector("form") );
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", "test.php",true); 
    xmlHttp.send(formData); 
    xmlHttp.onreadystatechange =  function(){
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200){ 
        alert(xmlHttp.responseText);
    }
}
}

ob = document.getElementById("submit"); 
ob.addEventListener("click",sendData);

Now i want to separate them

        if (xmlHttp.readyState == 4 && xmlHttp.status == 200){ 
        alert(xmlHttp.responseText);

in a single function.

I rewrite the test1.js as test2.js.

var xmlHttp;
function ready(){        
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200){ 
        alert(xmlHttp.responseText);
        }
}

function sendData()
{
    var formData = new FormData( document.querySelector("form") );
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", "test.php",true); 
    xmlHttp.send(formData); 
    xmlHttp.onreadystatechange =  ready;
}

ob = document.getElementById("submit"); 
ob.addEventListener("click",sendData);

The test2.js encounter error info:

test2.js:4 Uncaught TypeError: Cannot read property 'readyState' of undefined
    at XMLHttpRequest.ready (test2.js:4)

Another issue :what is the right order for the following statements?
I have seen some material write them as below :

    xmlHttp.open("post", "test.php",true); 
    xmlHttp.send(formData); 
    xmlHttp.onreadystatechange =  function(){  }

Other material also seen:

    xmlHttp.onreadystatechange =  function(){  }
    xmlHttp.open("post", "test.php",true); 
    xmlHttp.send(formData); 

And other order in webpage xmlHttp statements order

xmlhttp.open("POST", "Demo", true);
xmlhttp.onreadystatechange=myCallBack;
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send("FirstName=Nat&LastName=Dunn");

Solution

  • In sendData you have:

    var xmlHttp = new XMLHttpRequest();
    

    Your only mistake is including the var here - just do this instead:

    xmlHttp = new XMLHttpRequest();
    

    The reason this matters is that the var is declaring a new local variable of the same name, which is then getting assigned to - so ready doesn't get access to it. It accesses the global xmlHttp variable, which is never assigned to. By removing the var as shown above, you ensure that the global variable is assigned to - and this should work. (Although of course it's not best practice to use globals.)