jquery .ajax json return on error

$.ajax({
    type: 'POST',
    url: api_url+'client/'+client.id+'.json', 
    data: {
        _method: 'delete',
        id: client.id
    },
    success: function(data) {
        $('#delete-client').html('Success');
    },
    error: function(data) {
        $('#delete-client').css('color', 'red');
        $('#delete-client').html('Error');
    }
});

On the error: function the jquery would recieve this json object with a 500 header status

{"errors":{"code":777,"message":"Method requested does not yet exist","data":[]}}

however if I use data.errors.message it doesnt show the error there. It shows a huge object with different events in chromes developer box when I console.log the return object its using

FIXED

var error = jQuery.parseJSON(jqXHR.responseText);
$('#delete-client').html(error.errors.message);
Answers

add : dataType:"json"...............

Try reading the $.ajax documentation:

error(jqXHR, textStatus, errorThrown) - Function

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, 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", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event.

Check the arguments list. That's not your data. That's a jqXHR object.


By definition, if you've successfully retrieved data from the server, you have succeeded, not errored. Data is data whether it contains the string "error" or not.

You should still be using the success callback, even though your data is describing an error. Don't send a 500 header.


$.ajax({
    type: 'POST',
    url: api_url+'client/'+client.id+'.json', 
    data: {
        _method: 'delete',
        id: client.id
    },
    success: function(data) {
        if(data.errors) {
            //Server not able to process the request
        }
        else {
            $('#delete-client').html('Success');
        }
    },
    error: function(data) {
        //AJAX request not completed
        $('#delete-client').css('color', 'red');
        $('#delete-client').html('Error');
    }
});