1

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 undefined how can I add a callback to prevent this from happening?

EDIT: a clarification on what I'm asking..

It's still returning undefined. I'm assigning the variable with the function send send returns onreadystatechange however when my code is executing.. response returns as undefined before send() can return. How do I stop the code under response from running on till response has been assigned sends value?

EDIT2:

The following code is my send function...

 function send(uri)
{
    var xhr = new XMLHttpRequest();
    xhr.open("POST",uri,true);
    xhr.onreadystatechange = function (send){
        if(xhr.readyState == 4){
            return xhr.responseText;
        }   
    }
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.send(null);
}
1
  • Please provide some code to get some better answers, very hard to give an answer without seeing some code. Commented May 16, 2011 at 11:16

4 Answers 4

2

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

function send(uri, callback)
{
    var xhr = new XMLHttpRequest();
    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, etc
            callback(xhr.responseText);
            //return 
        }   
    }
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.send(null);
}



function myFunction(){

  var myUrl = "foo.php";

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

  //Second half of your function that handles what you returned.
  function gotData( 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

function send(uri, callback)
{
    var xhr = new XMLHttpRequest();
    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{
        return null;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

@Skizit Then what's the question?
It's still returning undefined. I'm assigning the variable with the function send send returns onreadystatechange however when my code is executing.. response returns as undefined before send() can return. How do I stop the code under response from running on till response has been assigned sends value?
0

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.           
 }
};

Comments

0

try this:

function send(uri, callback)
{
    var xhr = new XMLHttpRequest();
    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
})

2 Comments

what if send takes parameters?
@Skizit: I can't know the answer without a good question :) try the new answer....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.