JQuery ajax call getting status code 0 "error"

Judith Adabie picture Judith Adabie · Feb 13, 2013 · Viewed 13.5k times · Source

I'm trying to call Petfinder.com to get a list of our pets. The url is http://api.petfinder.com/shelter.getPets?key=xxxxx&id=CA1469&format=json

The url seems to return the JSON fine. But when I try to make the call I'm getting "error" and status code 0. I tried using jsonp which results in a status of 200 but a parse error. If I change to xml I have the result of status 0 and "error".

 $.ajax({

         url: "http://api.petfinder.com/shelter.getPets?key=xxxx&id=CA1469&format=json",
         dataType: "json",
         type: "GET",
         success: function (data) {
             alert("hi");
         },
         error: function (jqXHR, exception) {
             if (jqXHR.status === 0) {
                 alert('Not connect.\n Verify Network.');
             } else if (jqXHR.status == 404) {
                 alert('Requested page not found. [404]');
             } else if (jqXHR.status == 500) {
                 alert('Internal Server Error [500].');
             } else if (exception === 'parsererror') {
                 alert('Requested JSON parse failed.');
             } else if (exception === 'timeout') {
                 alert('Time out error.');
             } else if (exception === 'abort') {
                 alert('Ajax request aborted.');
             } else {
                 alert('Uncaught Error.\n' + jqXHR.responseText);
             }

         }
     });

Answer

Kamil Szot picture Kamil Szot · Aug 25, 2014

You need to make sure that when server sends you error response it also sends proper CORS headers along with it.

If it doesn't browser won't allow your JavaScript code to see any infomation comming from that domain, even status code.