Javascript – test if URL is reachable using AJAX + cross-domain + jsonp

ajaxcross-domainjavascriptjquery

I'm using JQuery to fetch information from an URL and display it on my page asynchronously. The URL comes from other domain, so I use JSONP to get the data. That works fine.

However, when the remote URL is down (which happens once in a while) my page hangs as JQuery AJAX doesn't call the 'success' or 'error' functions.

I'm using JQuery 1.7.

My code looks like:

    $.ajax({
        type : "GET",
        url : "http://otherdomain.com/somePage.html",
        data : params,
        dataType : "jsonp",
        jsonp : "jsonp",

        success : function (response, textS, xhr) {
            alert("ok");
        },
        error : function (xmlHttpRequest, textStatus, errorThrown) {
            alert("not ok " + errorThrown);
        }
    });

If "somePage" is up, then I see the message "ok". If "somePage" is not reachable, then I don't see anything.

Any ideas on how can I get "error" function get called? Or more importantly, how to detect if the cross-domain URL is reachable?

Is that even possible?

Thanks,

Best Answer

add a timeout

$.ajax({
        type : "GET",
        url : "http://otherdomain.com/somePage.html",
        data : params,
        timeout:3000,
        dataType : "jsonp",
        jsonp : "jsonp",

        success : function (response, textS, xhr) {
            alert("ok");
        },
        error : function (xmlHttpRequest, textStatus, errorThrown) {
            alert("not ok " + errorThrown);
             if(textStatus==='timeout')
              alert("request timed out");
        }
    });

DEMO