2

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 
5
  • Just put the "Some code here that uses the short URL" instead of the "Do something" code.. Commented Nov 21, 2011 at 13:45
  • sync ajax is the devil. never use it. Commented Nov 21, 2011 at 13:49
  • While it is possible to use (or to mimic) a syncronous AJAX (XMLHTTPRequest) but it is not the ideal for many reason but the principal is Javascript has a limited process time. So, if the process takes more time to return then Javascript will hang with a message saying that the script is taking too much time (in almost all browser but Iexplorer). Commented Nov 21, 2011 at 13:50
  • @Raynos Could you tell me why? I've always seen AJAX-Calls as asynchronous, but recently heard about the sync-calls. What's so bad about them? thanks! edit oh, just saw magallanes - comment, so I guess that's the "devil" - part of it :D Commented Nov 21, 2011 at 13:54
  • @GNi33 they freeze (or crash for IE9) the entire browser whilst doing the XHR. This means all I can do is stare at a white screen until your doing with the XHR. That makes me rage Commented Nov 21, 2011 at 14:05

2 Answers 2

3

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(); 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.