Skip to content Skip to sidebar Skip to footer

How To Add Callback To Ajax Variable Assignment

I've got a variable responce which is assigned via an AJAX function send(). When I make the assignment... responce = send(); response returns before send does giving me back an und

Solution 1:

You are using Ajax in a asynchronous manner, but you are treating it to be synchronous.

Asynchronous calls goes off to do its job while the rest of the code after the initial send call executes. You are getting undefined because the code is not returning anything.

If you look at the XMLHttpRequest object, the 3rd argument in the open method is the asynchronous flag.

open("method", "URL"[, asyncFlag[, "userName"[, "password"]]])

Setting it to true [default is left off] will make an asynchronous call. Setting it to false will make it synchronous.

The problem with using synchronous calls is it locks up the user's browser until the call is returned. That means animated gifs stuff, browser timers stop, and so on. If the server takes forever to respond, the user can not do anything.

The best solution is to avoid using synchronous calls. Use the call back to continue the code execution flow.

So based on your edit, I will edit my response with a basic solution

functionsend(uri, callback)
{
    var xhr = newXMLHttpRequest();
    xhr.open("POST",uri,true);
    xhr.onreadystatechange = function (send){
        if(xhr.readyState == 4){  //You really should check for status here because you can get 400, 500, etccallback(xhr.responseText);
            //return 
        }   
    }
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.send(null);
}



functionmyFunction(){

  var myUrl = "foo.php";

  //show a loading message or soemthingvar someDiv = document.getElementById("loadingMessage");
  someDiv.style.display = "block";

  //Second half of your function that handles what you returned.functiongotData( value ){
      someDiv.style.display = "none";
      alert(value);
  }

  send(myUrl, gotData);

}

If you really want to do synchronous and you do not mind locking up a user's browser

functionsend(uri, callback)
{
    var xhr = newXMLHttpRequest();
    xhr.open("POST",uri,false);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.send(null);
    if(xhr.status==200){
        return xhr.responseText;
    }
    else{
        returnnull;
    }
}

Solution 2:

I presume you are talking about the XMLHTTPRequest.send() method, rather than a framework's wrapper.

send does not return anything. It will always return undefined.

To get the HTTP response, you need to monitor onreadystatechange, as countless StackOverflow answers and internet tutorials (e.g. this one) demonstrate.

Solution 3:

you must assign the value to your response on readystatechange event of your request, something like this:

req.onreadystatechange = function(){
 if (req.readyState===4) { // checks if data is already loaded.callback(req.responseText,req.status);  //call your callback function with response and status as parameters.           
 }
};

Solution 4:

try this:

functionsend(uri, callback)
{
    var xhr = newXMLHttpRequest();
    xhr.open("POST",uri,true);
    xhr.onreadystatechange = function (send){
        if(xhr.readyState == 4 and callback){
            callback();
        }   
    }
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.send(null);
}

send("uri here", function(){
    //whatever needs to be done after request
})

Post a Comment for "How To Add Callback To Ajax Variable Assignment"