C
C
codecreator2018-06-20 20:40:31
Django
codecreator, 2018-06-20 20:40:31

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

1 answer(s)
S
Sergey Gornostaev, 2018-06-20
@codecreator

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:
            ...

script.js (Bootstrap + jQuery)
$.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 question

Ask a Question

731 491 924 answers to any question