qwerty
qwerty

Reputation: 195

django + ajax output errors to the form

I use ajax to submit the form.

$(document).ready(function(){ 
   $(document).on("submit", "#my_form", function(event) {
    event.preventDefault(); 
   $this = $(this); 
   $.ajax({ 
    type: "POST",
    data: $this.serialize(), 
    success: function(data) 
    { console.log(data);
      if (data.result == 'success') {
       var parent=$("#my_form").parent();
       parent.html(data.success); }
       else if (data['result'] == 'error') {

      }
    }, 
    error: function(data) 
    { console.log(data); } 
  }); 
 }); 
});

when the form is valid, everything works fine. But I'm don’t understand how to display errors on the form if the field is entered incorrectly. They are displayed in the browser console. enter image description here

I deduce the form in the template as follows:

<form action="" method="post" autocomplete="off" id="my_form">
   {% csrf_token %}
  <div class="contact-form" >
   <h1>{%trans 'Register' %}</h1>
   <div class="txtb">{{form.fio.label}} {{form.fio}}{{form.fio.help_text}}</div>
   <div class="txtb">{{form.phone.label}} {{form.phone}}{{form.phone.help_text}}{{form.errors}}</div> 
   <div class="txtb"> {{form.date_visit.label}}{{form.date_visit}}</div>
   <div class="txtb"> {{form.captcha.label}}{{form.captcha}}{{form.errors}}</div>
   <input type="submit" value="{%trans 'subbmit' %}" class="btn" id="btn">   
  </div>
</form>

if you need code from views.py I can add. Help me please

Upvotes: 0

Views: 63

Answers (1)

Andrey Nelubin
Andrey Nelubin

Reputation: 3294

// before ajax send

$("#my_form p.error").remove();
$("#my_form input").removeClass('b-error')
...
$.ajax
...
if (data.result == 'success') {
    ...
} else if (data['result'] == 'error') {
    Object.keys(data['response'].forEach(function(key) {
        $("#my_form input[name='" + key +  "'")
            .addClass('b-error')
            .after('<p class="error">' + data['response'][key] + '</p>')
    })

}

Upvotes: 1

Related Questions