How do I get the HTTP status code with jQuery?

JqueryAjaxXmlhttprequestHttp Status-CodesHttp Status-Code-401

Jquery Problem Overview


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); 
    }
});

Jquery Solutions


Solution 1 - Jquery

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');
   },
});

Solution 2 - Jquery

The third argument is the XMLHttpRequest object, so you can do whatever you want.

$.ajax({
  url  : 'http://example.com',
  type : 'post',
  data : 'a=b'
}).done(function(data, statusText, xhr){
  var status = xhr.status;                //200
  var head = xhr.getAllResponseHeaders(); //Detail header info
});

Solution 3 - Jquery

Use the error callback.

For example:

jQuery.ajax({'url': '/this_is_not_found', data: {}, error: function(xhr, status) {
    alert(xhr.status); }
});

Will alert 404

Solution 4 - Jquery

I think you should also implement the error function of the $.ajax method.

> error(XMLHttpRequest, textStatus, > errorThrown)Function > > A function to be called if the request > fails. The function is passed three > arguments: The XMLHttpRequest object, > a string describing the type of error > that occurred and an optional > exception object, if one occurred. > Possible values for the second > argument (besides null) are "timeout", > "error", "notmodified" and > "parsererror".

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

Solution 5 - Jquery

I found this solution where you can simply, check the server response code using status code.

Example :

$.ajax({
type : "POST",
url : "/package/callApi/createUser",
data : JSON.stringify(data),
contentType: "application/json; charset=UTF-8",
success: function (response) {	
	alert("Account created");
},
statusCode: {
	403: function() {
       // Only if your server returns a 403 status code can it come in this block. :-)
		alert("Username already exist");
	}
},
error: function (e) {
	alert("Server error - " + e);
} 
});

Solution 6 - Jquery

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

Solution 7 - Jquery

I encapsulate the jQuery Ajax to a method:

var http_util = function (type, url, params, success_handler, error_handler, base_url) {

    if(base_url) {
        url = base_url + url;
    }

    var success = arguments[3]?arguments[3]:function(){};
    var error = arguments[4]?arguments[4]:function(){};



    $.ajax({
        type: type,
        url: url,
        dataType: 'json',
        data: params,
        success: function (data, textStatus, xhr) {

            if(textStatus === 'success'){
                success(xhr.code, data);   // there returns the status code
            }
        },
        error: function (xhr, error_text, statusText) {

            error(xhr.code, xhr);  // there returns the status code
        }
    })

}

Usage:

http_util('get', 'http://localhost:8000/user/list/', null, function (status_code, data) {
    console(status_code, data)
}, function(status_code, err){
    console(status_code, err)
})

Solution 8 - Jquery

I have had major issues with ajax + jQuery v3 getting both the response status code and data from JSON APIs. jQuery.ajax only decodes JSON data if the status is a successful one, and it also swaps around the ordering of the callback parameters depending on the status code. Ugghhh.

The best way to combat this is to call the .always chain method and do a bit of cleaning up. Here is my code.

$.ajax({
        ...
    }).always(function(data, textStatus, xhr) {
        var responseCode = null;
        if (textStatus === "error") {
            // data variable is actually xhr
            responseCode = data.status;
            if (data.responseText) {
                try {
                    data = JSON.parse(data.responseText);
                } catch (e) {
                    // Ignore
                }
            }
        } else {
            responseCode = xhr.status;
        }

        console.log("Response code", responseCode);
        console.log("JSON Data", data);
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhorgenView Question on Stackoverflow
Solution 1 - JqueryRavi MittalView Answer on Stackoverflow
Solution 2 - Jqueryb123400View Answer on Stackoverflow
Solution 3 - JquerybalooView Answer on Stackoverflow
Solution 4 - JqueryGvSView Answer on Stackoverflow
Solution 5 - JqueryJigar TrivediView Answer on Stackoverflow
Solution 6 - JqueryvartecView Answer on Stackoverflow
Solution 7 - JqueryaircraftView Answer on Stackoverflow
Solution 8 - JqueryPhilView Answer on Stackoverflow