Question

I'm trying to work my way out with XMLHttpRequest, but I've run into an issue:

function x(url, callback) { //edited

    xmlHttp.onreadystatechange = function() {
        if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) {
            callback(xmlHttp.responseText;) //edited
        } else {
            document.getElementById('content').innerHTML = '<div class="error">Ups, an error ocurred! Server response: <span>'+xmlHttp.responseText+'</span></div>';
        }
    }
    xmlHttp.open('GET', url, true);
    xmlHttp.send(null);
}

function y()
{
    var url = base_url + '?asa=test';
    x(url, function (response) { //edited
       console.log(response);
    });
}

But my problem is the if readyState == 4. The output of the console.log is always undefined and never enters the if, only else and that's because the first time the if is executed, readyState has the value of 1.

So, any way to work around that issue because it's making me crazy, I've tried everything I could think of for now.

UPDATE

The code's format, it's what I last tried because before I had it separated, in variables and all kinds of things that I tried to work around the issue

Btw, a console.log(xmlHttp.readyState) inside onreadystatechange's function, will output one by one: 1, 2, 3 and 4

Was it helpful?

Solution

As bergi said, the request is asynchronous. This means x returns immediately, and xmlHttp.onreadystatechange is called later. If you need to do something with the response from within y, pass it as a callback so x can call it when the time is right:

function x( callback )
{
    if( pseudocode: request is ok )
    {
        callback( response );
    }
}

function y()
{
    x( url, function( response )
    {
        // do something with the response.
    } );
}

UPDATE

xmlHttp.onreadystatechange is called with readyState 1, 2, and 3 before 4.

if( state === 4 )
{
    if( statuscode === 200 )
    {
        // success
    }
    else
    {
        // failure
    }
}
/*else
{
    ignore states 1, 2 and 3
}*/
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top