How to read a property from a JSON response when the HTTP response has a failure code?

431 Views Asked by At

I have this code:

$.post(Routing.generate('parMarcaModelo'), {
    "marcaId": currBranch,
    "modeloId": currModel,
    "marcaNombre": currBranchName,
    "modeloNombre": currModelName
}, 'json').done(function (data, textStatus, jqXHR) {
    // do something here
}).fail(function (jqXHR, textStatus, errorThrown) {
    // Catch error from server and logs to console
    var err = eval("(" + jqXHR.responseText + ")");
    colose.log('Error', err.Message, 20000);

    return false;
});

The server side returns a JSON like this one:

{
   "success":false,
   "error":"El par Marca2-Modelo1 ya existe. Por favor escoja otra combinaci\u00f3n.",
}

But also returns a 400 code so Ajax call will go through .fail() callback insted of .done(). Having this information, how I can catch the error key from the JSON in the .fail() to show to users?

I have found this code:

$.get('http://localhost/api').then(function(res) {
    var filter $.Deferred()

    if (res.success) {
        filter.resolve(res.data)
    } else {
        filter.reject(res.error)
    }

    return filter.promise()
}).done(function(data) {
    console.log('Name:',  data.name) // Outputs: Foo
}).fail(function(error) {
    console.log('Error:', error) // Outputs: Something bad happened.
})

On this topic at SO but does not know if is right and also if will affect my code in someway.

Any help or advice?

1

There are 1 best solutions below

7
On BEST ANSWER

You are sending in 'json' as the success callback function to $.post().

This is the correct function signature: jQuery.post( url [, data ] [, success ] [, dataType ] )


Clarification

This code will work, since it passes in an empty function in place of the 'success'.

$.post('rest.php', {data : 'data'}, function(){},'json').done(
function (data, textStatus, jqXHR) {
    // do something here
}).fail(function (jqXHR, textStatus, errorThrown) {
    // Catch error from server and logs to console
    console.log('Error', jqXHR.responseJSON, 20000);

    return false;
});

However, this code will not:

$.post('rest.php', {data : 'data'}, 'json').done(
function (data, textStatus, jqXHR) {
    // do something here
}).fail(function (jqXHR, textStatus, errorThrown) {
    // Catch error from server and logs to console
    console.log('Error', jqXHR.responseJSON, 20000);

    return false;
});

For proof, look at line 781-798 in the jQuery source code. If the data parameter is a function, e.g. the success callback, the items will get shifted. However, since this is not the case, every parameter will be put in by the position they appear in the function.

In the second version, Ajax.succees will be set to the string 'json' and the Ajax.dataType is set to undefined. The jqXHR.responseJSON of that version will return a undefined, since it's not parsed as JSON.

The first version, however, returns a JSON object.


Also, you wrote colose.log instead of console.log in your code. That might be why couldn't get the data.