Reputation: 6994
I'm using ajax to submit forms. This is a piece of code I wrote:
$.post(this.action, $(this).serialize())
.done(function(data) {
form.find(".success-msg").text(data);
})
.fail(function() {
// insert error msg to the form
})
.always(function() {
modal.modal("hide");
});
How can I get the server response in the fail handler? the .fail() callback does not get the returned data like .done() do..
Second, is it correct to return non 200 (say 40X) status for a form validation errors that occur on the server? Or I should return 200 OK status and somehow distinguish myself between error/success in my own response?
i.e on validation errors I can do this
return HttpResponse(error_msg)
or,
return HttpResponseBadRequest(error_msg)
Upvotes: 1
Views: 1275
Reputation: 732
This might be late but I had this same issue recently and this is my solution.
.error(function(xhr){
var result = xhr.responseJSON;
form.find(".error-message").text(result.data);
});
You can always console log xhr.responseJSON to be sure what's being returned.
Upvotes: 1
Reputation: 62556
In the done
part you have:
.done(function(data) {
form.find(".success-msg").text(data);
});
But in the fail
you didn't include the data
argument. You should include it if you want to use it:
.fail(function(data) {
// insert error msg to the form
});
Regarding the other question - if you know the reason for the fail - I think it's better to response with 200
and inside the response to have a status: true/false
and the rest of the data. This way you can use different functions/behavior if you got some other error code (server not responding/server error/etc).
Upvotes: 1