0

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

1 Answer 1

1
// 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>')
    })

}
Sign up to request clarification or add additional context in comments.

9 Comments

Why did I get an error only in the number? Is there a captcha?
I don't understand you. What number? What do you mean by last question?
when entering the wrong phone number and captcha, an error is displayed only in the number
I probably understood why. By default, django-simpel-captcha input have name captcha_1
I guess your view returns error response code and your error handler executes. Otherwise executes success`` executes. Try to console.log(arguments)``` in error handler to view all arguments.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.