GV1
GV1

Reputation: 475

XMLHttpRequest Synchronous or Asynchronous

In my JS I am sending a get request to the bit.ly api to shorted a URL. The problem is I need the URL returned for use in the code.

Would it be best to use a synchronous request for this? As it stands any code after the XHR request that uses the bit.ly would fail because the response has not yet returned the short URL.

bitlyXHR.onreadystatechange = function() {
    if (bitlyXHR.readyState == 4) {
        if (bitlyXHR.status == 200) {
            var obj = JSON.parse(bitlyXHR.responseText);
            // Do something
        }
    }
};

bitlyXHR.open("GET", "http://api.bitly.com/v3/shorten?login=&apiKey=&longUrl=" + longURL + "&format=json");
bitlyXHR.send();

// Some code here that uses the short URL

Upvotes: 2

Views: 4844

Answers (2)

tvanfosson
tvanfosson

Reputation: 532505

Move the code that uses the short URL to the section of the code that has the Do something comment or, even better, call a function that contains that code from there.

Doing it this way is called using a callback. You supply a function to be executed later when the request returns. This is the best way to handle an AJAX (the A stands for asynchronous, after all) request as it won't lock up your browser while waiting for the call to complete.

Upvotes: 0

pradeek
pradeek

Reputation: 22105

You can do something like this:

function doSomething(obj) {
    // this does something with the result.
}

bitlyXHR.onreadystatechange = function() {
    if (bitlyXHR.readyState == 4) {
        if (bitlyXHR.status == 200) {
           var obj = JSON.parse(bitlyXHR.responseText);
           doSomething(obj); 
        }
    }
};

bitlyXHR.open("GET", "http://api.bitly.com/v3/shorten?login=&apiKey=&longUrl=" + longURL + "&format=json");
bitlyXHR.send();

Upvotes: 3

Related Questions