Skip to content Skip to sidebar Skip to footer

Returning Ajax Responsetext From A Seperate File

This question may have been asked a million times in the past but I am yet to come across a solution. So I ask again, hoping a less aggressive answer like 'Look somewhere else'

Solution 1:

The gist of it has already been mentioned, but I would like to go into a bit more depth as to why this doesn't work.

You have the following code:

request.onreadystatechange = function() 
{
    if (request.readyState == 4)
    {
        document.write(request.responseText);
        return(request.responseText);
    }
}

Basically, you are setting the onreadystatechange event to the value of an anonymous function. In that anonymous function, you are returning a value, which won't be returned to the caller of ajax_phprequest(), but to the caller of the anonymous function, which is the event system and which doesn't care much about what value is returned.

This happens this way because it all happens asynchronously. In other words, you call ajax_phprequest() and all that happens at that moment happens behind the screens. The user can continue working like nothing has happened. However, in the background, the php file is requested and hopefully returned. When that happens, you get to use the contents, but the moment at which you called ajax_phprequest() has long since passed.

A proper way would be to use a callback function instead. It could look something like this:

functionajax_phprequest(data, php_file, callback)
{
    var request =  createXMLHttp();
    request.open("POST", php_file, true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send(data);
    request.onreadystatechange = function() 
    {
        if (request.readyState == 4)
        {
            document.write(request.responseText);
            callback(request.responseText);
        }
    }
}

functionfoo()
{
    ajax_phprequest("user=defuser&pass=123456","auth.php", function (text)
    {
        alert(text);
    });
}

Solution 2:

That is because the call is ASYNCHRONOUS so you cannot return from stack the usual way, i.e. your alert(ajax_phprequest("user=defuser&pass=123456","auth.php")); is evaluated before the ajax response is returned ... you need to use a callback:

function callback( text ){
    // something
}

...
if (request.readyState == 4){
    callback( request.responseText );
}

Post a Comment for "Returning Ajax Responsetext From A Seperate File"