1

I am trying to use a code created on JSFiddle by the stackoverflow user duotrigesimal for batch URL expanding, which is pasted below

var tests = [
'http://t.co/NJwI2ugt',
'http://www.google.com',
'http://www.goo.com',
'http://www.goog.com'
 ];

for (i in tests) {

var data = {
    url: tests[i],
    format: 'json'
};

$.ajax({
    dataType: 'jsonp',
    url: 'http://api.longurl.org/v2/expand',
    data: data,
    success: function (response) {
       $('#output').append(response['long-url']+ '<br>');
    }

});
}

In this case, it takes these four URLs and gives as output their expanded versions. However, it only does so when there is success. In the above 4 URLs, the 1st, 2nd, and 4th resolve to proper URLs and show up in the output but the 3rd one, which is an error is entirely skipped by the code. When an error is encountered, I want the code to display an error message or at least just skip by producing a line break and move on. Otherwise, I give in 4 shortened URLs and I get as output 3 and I don't know which one was the error. Can someone please help?

1 Answers1

0

It looks like the longurl api has a very long timeout, so we'll have to set a more reasonable one ourselves. This example has it set to 3 seconds, but you can adjust as needed.

Then, we just check if the response timed out and act accordingly.

Here is a jsFiddle for this.

var tests = [
'http://t.co/NJwI2ugt',
'http://www.google.com',
'http://www.asdkofhakisgjhasfjhbvasfdv.com',
'http://www.goog.com'
 ];

for (i in tests) {

var data = {
    url: tests[i],
    format: 'json'
};

$.ajax({
    dataType: 'jsonp',
    url: 'http://api.longurl.org/v2/expand',
    data: data,
    timeout: 3000,
    complete: function (response) {

        if( response.statusText == 'success' ) {
            $('#output').append('success: '+response.responseJSON['long-url']+'<br>');
        } else {
            $('#output').append('error: error message here <br>');
        }    


    }, 

});
}
Jonathan Wren
  • 3,662
  • 23
  • 29