85

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); 
    }
});
Serge
  • 1,947
  • 3
  • 26
  • 48
horgen
  • 2,183
  • 10
  • 30
  • 34
  • Check the value of `statusText`, the second parameter to the callback function instead. – Jimmy Jun 02 '10 at 08:16
  • 1
    this alerts "Authorization Required". Ican work with that, but a 401 alert would be better ;) – horgen Jun 02 '10 at 09:12

9 Answers9

106

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');
   },
});
Gung Foo
  • 13,392
  • 5
  • 31
  • 39
Ravi Mittal
  • 1,261
  • 2
  • 9
  • 11
76

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
});
b123400
  • 6,138
  • 4
  • 27
  • 27
  • It returns this: XMLHttpRequest cannot load http://example.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://stackoverflow.com' is therefore not allowed access. – sidney Mar 28 '15 at 21:38
  • You will have to enable CORS handling to get rid of the 'Access-Control-Allow-Origin' issue. Depending on what type of project you are dealing with, you may not be able to simply resolve this especially if the API is in a different domain and that doesn't allow cross domain requests – Anjan Biswas Apr 25 '17 at 08:57
  • @Annjawn How to handle CORS , as if i make same API call with Php it doesn't give any error of CORS but if i was ajax for that same API call i gives Error of CORS. Please let me know – MD Shahrouq Feb 22 '18 at 08:03
  • 4
    This will not work if the status code is 400 (and probably for other codes that are not 200) – Johann Feb 26 '18 at 10:39
21

Use the error callback.

For example:

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

Will alert 404

baloo
  • 7,635
  • 4
  • 27
  • 35
  • indeed it did. I'm kinda new to jQuery. But what about 401 status? How do i save the status to a variable? o_O – horgen Jun 02 '10 at 08:46
  • It will show 401 the same way. What exactly do you want to do with the error? – baloo Jun 02 '10 at 08:55
  • If 401 dont send user to this page. The error only alerts if the page is not found (404) – horgen Jun 02 '10 at 09:05
  • Tested this in Firefox where it catched 401 as well, perhaps this is not true for all browsers – baloo Jun 02 '10 at 09:13
10

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); 
    }
});
aircraft
  • 25,146
  • 28
  • 91
  • 166
GvS
  • 52,015
  • 16
  • 101
  • 139
  • 3
    thx, but complete only returns 0. Is it possible to get the 401 code? – horgen Jun 02 '10 at 08:56
  • Are you sure complete is called when a HTTP 401 (Unauthorized) is returned from the server? I have not tested, but I would expect that error is called. – GvS Jun 02 '10 at 09:16
  • complete Type: Function( jqXHR jqXHR, String textStatus ) A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. – pshirishreddy May 24 '13 at 04:58
9

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);
} 
});
erip
  • 16,374
  • 11
  • 66
  • 121
Jigar Trivedi
  • 131
  • 1
  • 3
6
$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});
vartec
  • 131,205
  • 36
  • 218
  • 244
3

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)
})
aircraft
  • 25,146
  • 28
  • 91
  • 166
1

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);
    });
Phil
  • 1,996
  • 1
  • 19
  • 26
1

Using Jquery get v.3.3.1.

var reqUrl = '/your/web/url';
$.get(reqUrl, function(data, status, xhr){
       console.log("Data: " + JSON.stringify(data) + "\nStatus Code: " + xhr.status); 
}, 'json');
Johan
  • 207
  • 4
  • 14