Q:

Chrome-Extension: Why is my response returning before the AJAX call?

I'm making an AJAX call from my popup.html like so..
chrome.extension.sendRequest(
                    {
                        req: "send",
                        url: requrl
                    },
                    function(response)
                    {
                        console.log("RESPONSE:" + response.reply);
                    });

This code goes to the following case in background.html...
                case "send":
                sendResponse({
                    reply: send(request.url)
                });
                break;

which in turn calls the following...
    function send(uri)
{
    var xhr = new XMLHttpRequest();
    xhr.open("POST",uri,true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.onreadystatechange = function (send){
        if(xhr.readyState == 4){
            return xhr.responseText;
        }
    }
    xhr.send(null);
}

My problem is that my code is returning undefined before send() has a chance to respond. How can I make my code wait for a response? I need to keep this call asynchronous because I need the UI not frozen to display a progress dialog.

A:

The reason you're getting undefined back is that that is the result of the send function. If you take a look at the function as it stands, it exits after send(null). The return statement will not execute until some time later, and by then nothing will be there to receive it.
If you want to respond when the XHR request completes, you need to use a callback.
In brief:
case "send:"
  send(request.url, function(response) {
    sendResponse(response);
  })

function send(uri, callback) {
  ...
  xhr.onreadystatechange = function (send){
    if(xhr.readyState == 4){
      callback(xhr.responseText);
    }
  }
  ...
}

c.f. other asynchronous callback questions.

