Reputation: 18680
I'm trying to trigger a Bootstrap Growl message if $.post
call fails. How I know if it fails? Because backend part (PHP script) returns this JSON:
{
"success":false,
"errors":{
"usuario":{
"captcha":[
"The captcha is not valid."
]
}
}
}
So I did this in jQuery:
$.post($form.attr('action'), $form.serialize(), function(result) {
// ... Process the result ...
}, 'json').fail(function(result) {
console.log("fail");
$.growl({
icon: "fa fa-paw",
title: "<strong>Error en datos</strong>",
message: "Los siguientes errores ocurrieron",
type: "danger",
allow_dismiss: true,
animate: {
enter: 'animated bounceInDown',
exit: 'animated bounceOutUp'
}
});
});
But none the message or the console.log()
works so I don't know if the right is .fail()
or .error()
or all the time is success and then I need to verify if success
at JSON comes with FALSE
which means some error.
As a second little question, how I move inside the JSON looking for errors strings for show them as LI inside the message
at Growl element?
Upvotes: 0
Views: 311
Reputation: 91
I think you are confusing a captcha failure and an ajax call failure as the same thing, if I am interpreting your question correctly, that is.
The ajax call itself is succeeding, which is why you see none of the ajax failure output. The JSON returned by the SUCCESSFUL call contains information(success:"false") stating that the captcha entry failed to pass it's test. Does that make sense?
You will need to take the success attribute in the result JSON and apply appropriate actions depending on it being a success true or false.
Upvotes: 1
Reputation: 8499
Try this code:
$.post($form.attr('action'), $form.serialize(), function(result) {
//code for success
if (result.success) {
//TODO
}
//code for failure
if (!result.success) {
console.log("fail");
$.growl({
icon: "fa fa-paw",
title: "<strong>Error en datos</strong>",
message: "Los siguientes errores ocurrieron",
type: "danger",
allow_dismiss: true,
animate: {
enter: 'animated bounceInDown',
exit: 'animated bounceOutUp'
}
});
}//if failed
},
'json');
Upvotes: 1
Reputation: 15809
The fail clause will be triggered if the response contains an http error, for example, a 400 or a 500. If the http response is 200 - ok, then you won't get a failure.
Upvotes: 2