How do I get the HTTP status code with jQuery?

horgen picture horgen · Jun 2, 2010 · Viewed 171.4k times · Source

I want to check if a page returns the status code 401. Is this possible?

Here is my try, but it only returns 0.

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
    alert(xhr.status); 
    }
});

Answer

Ravi Mittal picture Ravi Mittal · Sep 27, 2012

this is possible with jQuery $.ajax() method

$.ajax(serverUrl, {
   type: OutageViewModel.Id() == 0 ? "POST" : "PUT",
   data: dataToSave,
   statusCode: {
      200: function (response) {
         alert('1');
         AfterSavedAll();
      },
      201: function (response) {
         alert('1');
         AfterSavedAll();
      },
      400: function (response) {
         alert('1');
         bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
      },
      404: function (response) {
         alert('1');
         bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
      }
   }, success: function () {
      alert('1');
   },
});