Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing XMLHttpRequest.responseText into variable [duplicate]

Not very familiar with XMLHttpRequests, but am using the cross-origin function in Google Chrome extensions. This works great (I can confirm I get the appropriate data that I need), but I can't seem to store it within the 'response' variable.

I'd appreciate any help.

function getSource() {
    var response;
    var xmlhttp;

    xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
             response = xmlhttp.responseText;
                 //IM CORRECTLY SET HERE
        }
        //I'M ALSO STILL WELL SET HERE
    }
    //ALL OF A SUDDEN I'M UNDEFINED.

    xmlhttp.open("GET","http://www.google.com",true);
    xmlhttp.send();

    return response; 
}
like image 301
Albert Avatar asked Oct 06 '13 20:10

Albert


1 Answers

The onreadystatechange function is asynchronous, that is it will not stop later code from running before the function has completed.

For this reason, you're going about this entirely the wrong way. Typically in asynchronous code, callbacks are employed to be able to be called exactly when the onreadystatechange event fires, so that you know that you are able to retrieve your response text at that time. For example, this would be a case of an asynchronous callback:

function getSource(callback) {
    var response, xmlhttp;

    xmlhttp = new XMLHttpRequest;
    xmlhttp.onreadystatechange = function () {
      if (xmlhttp.readyState === 4 && xmlhttp.status === 200 && callback) callback(xmlhttp.responseText);
    }

    xmlhttp.open("GET", "http://www.google.com", true);
    xmlhttp.send();
}

Think of it like using setTimeout, which is also asynchronous. The following code will not hang for 100 000 000 000 000 seconds before ending, but rather end immediately, and then wait for the timer to be up to run the function. But by then, the assignment is useless, as it isn't global and nothing else is in the scope of the assignment.

function test()
{   var a;
    setTimeout(function () { a = 1; }, 100000000000000000); //high number for example only
    return a; // undefined, the function has completed, but the setTimeout has not run yet
    a = 1; // it's like doing this after return, has no effect
}
like image 72
Qantas 94 Heavy Avatar answered Oct 14 '22 11:10

Qantas 94 Heavy