Answer the question
In order to leave comments, you need to log in
How to display an error via Ajax?
Good afternoon. There is ajax, which checks the nickname for employment. In the view, the check passes. How can I display the validation result (error) in a form using ajax? What answer should be returned?
When submitting the form, errors are displayed like this:
form.errors['__all__'] = form.error_class([...])
Answer the question
In order to leave comments, you need to log in
views.py
class SomeFormHandler(FormView):
def form_invalid(self, form):
if self.request.is_ajax():
data = {'status': 'error', 'erros': []}
for field, errors in form.errors.items():
for error in errors:
data['errors'].append({'key': field, 'desc': error})
return JsonResponse(data)
else:
...
$.post($(form).attr('action'), $(form).serialize(), function(result) {
if(result.status == 'ok') {
form.reset();
showAlert('Сообщение успешно отправлено', 'success');
}
else if(result.status == 'error') {
for(var ndx in result.errors) {
if(result.errors[ndx].key == '__all__') showAlert(result.errors[ndx].desc);
$(form).find('[name=' + result.errors[ndx].key + ']').parent().addClass('has-error');
}
}
}).fail(function(xhr, textStatus, error) {
showAlert('Ошибка отправки сообщения');
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question