Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble reading Javascript code

I'm new in JS, and having quite hard time reading the following JS code.

The first parameter of the function is a url to a PHP script, the second is a string.

What confuses me is how to read code after the line: self.xmlHttpReq.open('POST', strURL, true);

What happens after this? Which code should i look after this line? The script? What happens after open?

function check_detail(strURL, pids) 
{
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() 
    {
        if (self.xmlHttpReq.readyState == 4)
            updatepage(self.xmlHttpReq.responseText, pids);
    }
    self.xmlHttpReq.send(getquery(pids));
}
like image 649
Tool Avatar asked Jan 27 '26 20:01

Tool


2 Answers

The key is the call to "send()", which actually launches the HTTP request. That happens, but the code then proceeds immediately without waiting for the result.

When the server responds, the browser will invoke the anonymous function set up as the "readystatechange" handler. Exactly when that happens is unpredictable; it's asynchronous, in other words.

Thus, the "updatepage()" call will happen long after the "check_detail()" function has returned.

like image 60
Pointy Avatar answered Jan 29 '26 10:01

Pointy


When you make an Ajax request (which is what you are doing here) it is asynchronous, which means that you don't know exactly when it will return so you can't just wait for the return.

Instead, you set up your function so that, when the request returns, a function is kicked off to handle the response. This is the onreadystatechange piece.

So the chronology will be: first the send() will occur, which will send the result of the getquery() method up to the PHP page. When that returns, the function defined within onreadystatechange will fire, which will call updatepage() and pass it both the text that was sent back from the Ajax call, and also the pids parameter.

like image 28
Jacob Mattison Avatar answered Jan 29 '26 08:01

Jacob Mattison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!