Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling 404 bad request in getJSON() jquery

Tags:

rest

jquery

jsonp

I have the following code and I am retrieving JSON from a site using JSONP. I want to handle error code like 404 bad request. Following is not working for me.

$.getJSON('https://xyz.com/search?jsonp-callback=?', function(data) {

  alert("success");
})
.success(function() { alert("success 2"); })
.error(function() { alert("error occurred "); })
.complete(function() { alert("Done"); });

Success and complete methods are working but error method is not working.

like image 315
dejavu Avatar asked Feb 25 '13 10:02

dejavu


3 Answers

Try fail instead of error (see the Deferred doc).

like image 61
LeGEC Avatar answered Oct 15 '22 14:10

LeGEC


$.getJSON('https://xyz.com/search?jsonp-callback=?', function(data) {
  alert("success");
})
.success(function() { alert("success 2"); })
.error(function(event, jqxhr, exception) {
    if (jqxhr.status == 404) {
              alert("error occurred ");   
    }
})
.complete(function() { alert("Done"); });

Above code may help you.

like image 4
Mallikarjuna Reddy Avatar answered Oct 15 '22 15:10

Mallikarjuna Reddy


This thread has the answer : https://stackoverflow.com/a/14371049/685925

Since you're using JSONP, the callback created by jQuery isn't called so the failure callback never gets called. That's the normal behavior for JSONP, alas.

like image 1
Vala Avatar answered Oct 15 '22 14:10

Vala