How to callback a function on 404 in JSON ajax request with jQuery?

shingara picture shingara · Mar 22, 2010 · Viewed 31.5k times · Source

I want to make an Ajax request with response in JSON. So I made this Ajax request:

$.ajax({
    url: 'http://my_url',
    dataType: "json",
    success: function(data){
      alert('success');
    },
    error: function(data){
      alert('error');
    },
    complete: function(data) {
      alert('complete')
    }})

This code works good but when my url send me a HTTP code 404, no callbacks are used, even the complete callback. After research, it's because my dataType is 'json' so 404 return is HTML and the JSON parsing failed. So no callback.

Have you a solution to call a callback function when a 404 is raised ?

EDIT: complete callback don't call is return is 404. If you want an URL wit 404 you can call : http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697 it's with this URL I have my problem.

Answer

Dustin Laine picture Dustin Laine · Mar 22, 2010
$.ajax({
    url: 'http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697',
    dataType: "json",
    success: function(data) {
        alert('success');
    },
    error: function(data) {
        alert('error');
    },
    complete: function(xhr, data) {
        if (xhr.status != 0)
             alert('success');
        else
             alert('fail');
    }
})