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?
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'.
However, this code will not:
For proof, look at line 781-798 in the jQuery source code. If the
dataparameter is a function, e.g. thesuccesscallback, 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.succeeswill be set to the string'json'and theAjax.dataTypeis set toundefined. ThejqXHR.responseJSONof that version will return aundefined, since it's not parsed as JSON.The first version, however, returns a JSON object.
Also, you wrote
colose.loginstead ofconsole.login your code. That might be why couldn't get the data.