P
P
pavvel22017-02-14 10:48:16
JavaScript
pavvel2, 2017-02-14 10:48:16

How to send ajax after error?

Good afternoon.
I'm not strong in javascript , the sending code was written by "poke method", everything works and sending and errors, but the problem is that after trying to send a form with empty fields, it gives a message about empty fields, and after filling them out, the script does not send, you need to click on the button 2 times .

Here is the sending script itself, if it's not difficult for knowledgeable people, please check it for errors.

$("form").submit(function(ev) {
        
        
      // Prevent the form from actually submitting
        ev.preventDefault();
    
        // Get the post data
        var data = $(this).serialize();
    
        // Send it to the server
        $.post('/', data, function(response) {
            
             
        });
        
    var ref = $(this).find("[required]");

    $(ref).each(function(){
        if ( $(this).val() == '' )
        {   
            $('.success-message').hide();
            $('.error-message').fadeIn();
           
            $(this).focus();

            ev.preventDefault();
            return false;
        }
        
            else {
            
                        $('.error-message').hide();      
                        $('.success-message').fadeIn().delay(2000).fadeOut();
      
                        } 

    });  return true;
});


Messages:
<div class="error-message" style="display: none;">
    	<p>Заполните все поля пожалуйста!</p>
    </div>
    <div class="success-message" style="display: none;">
    	<p>{{ form.afterSubmitText|default('Thanks for your submission.'|t) }}</p>
    </div>

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Leonovich, 2017-02-14
@pavvel2

Try changing the order of code execution - validation first, then dispatch, then done callback.

$("form").submit(function(ev) {
    var $form = $(this);
    // Prevent the form from actually submitting
    ev.preventDefault();
        
    var ref = $form.find("[required]");

    $(ref).each(function(){
        if ( $(this).val() == '' ) {   
            $('.success-message').hide();
            $('.error-message').fadeIn();
           
            $(this).focus();
        }  else {
            $('.error-message').hide();      

            // Get the post data
            var data = $form.serialize();
    
            // Send it to the server
            $.post('/', data, function(response) {
                $('.success-message').fadeIn().delay(2000).fadeOut();
            });
        } 

    });  
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question