70

I've created the server REST API to return a response with HTTP code and a JSON (or XML) object with more details: application code (specific to scenario, message that describe what happened etc.).

So, for example, if a client sends a Register request and the password is too short, the response HTTP code will be 400 (Bad Request), and the response data will be: {appCode : 1020 , message : "Password is too short"}.

In jQuery, I'm using the "AJAX" function to create a POST request. When the server returns something different from HTTP code 200 (OK), jQuery defines it as "error".

The error handler can get 3 parameters: jqXHR, textStatus, errorThrown. How can I get the JSON object that is sent by the server in an error case?

  1. Here is my JavaScript code:

    function register (userName, password) {
        var postData = {};
        postData["userName"] = userName;
        postData["password"] = password;
    
        $.ajax ({
            dataType: "json",
            type: "POST",
            url: "<server>/rest/register",
            data: postData,
            success: function(data) {
                showResultSucceed(data);
                hideWaitingDone();
            },
            error: function (jqXHR, textStatus, errorThrown) {
    
                showResultFailed(jqXHR.responseText);
                hideWaitingFail();
            }
        })
    }
    
  2. When looking at Firebug console, it seems like the response is empty. When invoking the same request by using REST testing tool, I get a response with JSON object it it.

What am I doing wrong?

2
  • 1
    In case you don't make it as far down as the accepted answer; there is nothing wrong with this code, the problem lies elsewhere. Commented Jan 16, 2013 at 21:22
  • For other future readers, I had a similar problem as well, and while the cross domain issue was completely irrelevant to my case, it turned out the problem was server side. (It seems the server code was broken in such a way that some combination of HTTP headers like Accept made it fail to return the correct response body on a 400 error.) Commented Sep 5, 2015 at 19:31

3 Answers 3

67

Here's an example of how you get JSON data on error:

$.ajax({
    url: '/path/to/script.php',
    data: {'my':'data'},
    type: 'POST',
    dataType: 'json'
}).fail(function($xhr) {
    var data = $xhr.responseJSON;
    console.log(data);
});

From the docs:

If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.

Otherwise, if responseJSON is not available, you can try $.parseJSON($xhr.responseText).

Sign up to request clarification or add additional context in comments.

1 Comment

"$.parseJSON($xhr.responseText)" is the key!. If instead of using ".fail" you use error: function(xmlHTTP, status, httperror) { $.parseJSON(xmlHTTP.responseText); }
32

directly from the docs

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader()

so use the jqXRH argument and get the responseText property off it.

In the link above, look for the section entitled

The jqXHR Object

4 Comments

@gdoron added the link and section to look for
@tibo, then show us your code. Something is off. Might be best to pause execution in your handler with firebug or webkit and just look at the properties of the arguments. It's gotta be there somewhere...
without actually digging in, I'm not sure at this point. Are you sure the response body is empty in firebug? Are you sure the url is correct? Are you sure the error handler is being called?
This should be the accepted answer - the code in the question is correct. The problem was entirely outside the realm of information provided.
4

I also faced same problem when i was using multipart/form-data. At first I thought multipart/form-data created this mess, but later i found the proper solution.

1) JS code before:

var jersey_url = "http://localhost:8098/final/rest/addItem/upload";
var ans = $.ajax({
    type: 'POST',
    enctype: 'multipart/form-data',
    url: jersey_url,
    data: formData,
    dataType: "json",
    processData: false,
    contentType: false 
    success : funtion(data){
      var temp = JSON.parse(data);
      console.log("SUCCESS : ", temp.message);  
    }
    error : funtion($xhr,textStatus,errorThrown){
       console.log("ERROR : ", errorThrown);
       console.log("ERROR : ", $xhr);
       console.log("ERROR : ", textStatus);
    }
    });

Here when error occurred, it showed me this in console :-
Error :
Error : { abort : f(e), always : f(), .... , responseJSON :"{"message":"failed"}" }
Error : error

Thus i came to know that we have to use $xhr.responseJSON to get the string message which we sent from rest api.

2) modified/working error funtion:

error : funtion($xhr,textStatus,errorThrown){
        var string= $xhr.responseJSON;
        var json_object= JSON.parse(string);
        console.log("ERROR : ",  json_object.message);
    }

Thus will output "Error : failed" on console.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.