Search code examples
jqueryapirestjqxhr

Jquery $.get to read header status on error


I'm writing a REST api. It returns a header status 400 on error.

However, on the AJAX side, I couldn't get the jqxhr object returned.

$.get('site.php', function(data, status, jqxhr) function(data) {
    //...
}).error(console.log(jqxhr));

it returns Uncaught ReferenceError: jqxhr is not defined.
In inspector console, its showing 400 (Bad Request) for the get request.

How do I get the text Bad Request?

I could return the text error within data by passing it in header status 200, but that's not the right approach am I correct?


Solution

  • The error function wants a callback function but you're executing console.log(jqxhr) and trying to hand its return value to error as the callback, that's where you're "jqxhr is not defined" error comes from.

    You want something like this:

    $.get('site.php', function(data, status, jqxhr) function(data) {
        //...
    }).error(function(jqXHR, textStatus, errorThrown) {
        // Do something interesting.
    });
    

    You should also be using fail instead of error as error is going away:

    Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.