How to handle error In $.get()

ajax, jquery

Solution

As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise.

var jqxhr = $.get( "example.php", function() {
    alert( "success" );
})
.done(function() {
    alert( "second success" );
})
.fail(function() {
    alert( "error" );
})
.always(function() {
    alert( "finished" );
});

Problem

I have a jquery code in which I am using get() and calling some remote url/file. Now I want to know what the best way is to handle errors from this. What I am doing is: ``` $(document).ready(function() { $.ajaxSetup({ error: function(x, e) { if (x.status == 0) { alert(' Check Your Network.'); } else if (x.status == 404) { alert('Requested URL not found.'); } else if (x.status == 500) { alert('Internel Server Error.'); } else { alert('Unknow Error.\n' + x.responseText); } } }); $.get("HTMLPage.htm", function(data) { alert(data); $('#mydiv').html(data); }); }); ``` This is working fine.But want to know is there any better way of doing this? ref:http://www.maheshchari.com/jquery-ajax-error-handling/

Original source