views:

613

answers:

3

If I am within my XHR's onreadystatechange function, I can easily do document.title = xhr.responseText, but if I make the function return the responseText, I can't set a variable equal to my XHR's outerlying wrapper to make it equal the response; is there any way to go about doing this?

My wrapper:

ajax = function(url, cb)
 {
    xhr = (window.XMLHttpRequest)
     ? new XMLHttpRequest()
     : new ActiveXObject('Microsoft.XMLHTTP');
    xhr.onreadystatechange = function()
     {
     if (xhr.readyState == 4 && xhr.status == 200)
      {
      cb(xhr.responseText);
      };
     }
    xhr.open('get', url, true);
    xhr.send();
 };

Now, if I did something like:

ajax('bacon.txt', function(_)
 {
    document.title = _;
 }

it works absolutely perfectly; document.title does in fact become the responseText of the call to bacon.txt. If, however, I try to implement it this way:

document.title = ajax('bacon.txt', function(_)
 {
    return _;
 }

no such luck. Can anybody clarify as to why this is? };

+5  A: 

You're assigning the return of the ajax function to the title. The ajax function itself doesn't return anything.

The whole point of AJAX is that the function return immediately it has made the request to the server, before any response is received. You are assigning undefined to the title property (BTW, I usually have my ajax function return the xhr being used allowing me to abort if necessary).

When the request is complete the callback (the cb in your code) function is called, hence your original code makes sense, it does the assigning.

AnthonyWJones
+1: If you add "return 'sent request';" after xhr.send(); you may be enlightened.
Greg
A: 

the result of the onreadystatechange function is not the same your "ajax" funcion... You could make your post sync, and make the ajax function return the same, but it will end up delaying the user response in the browser if the response takes too long.

The better you could do is finding another way of doing that, as you prefer. I mean, don't try to make it work that way because it will be worse.

Diego Jancic
A: 

Use jQuery or similar

Why re-invent the wheel?

This problem has been solved perfectly many years ago

TFD