How to get HTTP status code using jQuery?

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

Here is my attempt, but it returns 0.

$.ajax({ url: "http://my-ip/test/test.php", data: {}, complete: function(xhr, statusText){ alert(xhr.status); } }); 
+49
Jun 02 '10 at 8:09
source share
6 answers

this is possible using the 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'); }, }); 
+75
Sep 27 '12 at 17:31
source

The third argument is an 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 }); 
+52
Aug 13 '13 at 6:15
source

Use error callback.

For example:

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

Will warn 404

+17
Jun 02 '10 at 8:17
source

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

error (XMLHttpRequest, textStatus, errorThrown) Function

Function called if the request fails. The function is passed three arguments: an XMLHttpRequest object, a string describing the type of error it happened and an exception object if it happened. Possible values ​​for the second argument (other than zero) are timeout, error, unmodified, 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); } }); 
+6
Jun 02 '10 at 8:17
source
 $.ajax({ url: "http://my-ip/test/test.php", data: {}, error: function(xhr, statusText, errorThrown){alert(xhr.status);} }); 
+5
Jun 02 '10 at 8:19
source

I found this solution where you can simply check the server response code using the 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); } }); 
+4
Jun 05 '15 at 9:48
source



All Articles