Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make XHR.onreadystatechange return its result?

I'm new to JavaScript programming. I'm now working on my Google Chrome Extension. This is the code that doesn't work... :P

I want getURLInfo function to return its JSON object, and want to put it into resp. Could someone please fix my code to get it work?

function getURLInfo(url)
{
    var xhr = new XMLHttpRequest();
    xhr.open
        (
            "GET",
            "http://RESTfulAPI/info.json?url="
                + escape(url),
            true
        );
    xhr.send();
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState == 4)
        {
            return JSON.parse(xhr.responseText);
        }
    }
}
var resp = getURLInfo("http://example.com/") // resp always returns undefined...

Thanks in advance.

like image 248
Japboy Avatar asked Mar 19 '11 13:03

Japboy


People also ask

What is XHR Onreadystatechange?

XMLHttpRequest. onreadystatechange onreadystatechange property contains the event handler to be called when the readystatechange event is fired, that is every time the readyState property of the XMLHttpRequest changes. Warning: This should not be used with synchronous requests and must not be used from native code.

How does Onreadystatechange work?

The onreadystatechange property defines a function to be executed when the readyState changes. The status property and the statusText property holds the status of the XMLHttpRequest object. Holds the status of the XMLHttpRequest. The onreadystatechange function is called every time the readyState changes.


1 Answers

You are dealing with an asynchronous function call here. Results are handled when they arrive, not when the function finishes running.

That's what callback functions are for. They are invoked when a result is available.

function get(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            // defensive check
            if (typeof callback === "function") {
                // apply() sets the meaning of "this" in the callback
                callback.apply(xhr);
            }
        }
    };
    xhr.send();
}
// ----------------------------------------------------------------------------


var param = "http://example.com/";                  /* do NOT use escape() */
var finalUrl = "http://RESTfulAPI/info.json?url=" + encodeURIComponent(param);

// get() completes immediately...
get(finalUrl,
    // ...however, this callback is invoked AFTER the response arrives
    function () {
        // "this" is the XHR object here!
        var resp  = JSON.parse(this.responseText);

        // now do something with resp
        alert(resp);
    }
);

Notes:

  • escape() has been deprecated since forever. Don not use it, it does not work correctly. Use encodeURIComponent().
  • You could make the send() call synchronous, by setting the async parameter of open() to false. This would result in your UI freezing while the request runs, and you don't want that.
  • There are many libraries that have been designed to make Ajax requests easy and versatile. I suggest using one of them.
like image 104
Tomalak Avatar answered Nov 02 '22 02:11

Tomalak