Skip to content Skip to sidebar Skip to footer

AJAX-PHP Stay On Same Page If Validation Fails

I have a validation check with ajax and it will show errors. However, it will show the error and then immediately go to the form send page displaying the errors. The page is incred

Solution 1:

Try using addEventListener, then call event.preventDefault() to stop the form from submitting if there is an error, like this:

$('#submit_form').addEventListener('click', function (event) {

// Prevents form from submitting
             event.preventDefault();

   $.ajax({
       type: "POST",
       url: "submit_form.php",
       dataType: "json",
       data: $('#form_1').serialize(),
       success: function (json) {
        $('.message_center').html('');

        if(json['success']) {

         $('.message_center')
          .html('<div class="row">'+
            '   <div class="col-md-12">'+
            '     <div class="alert alert-success alert-dismissible">'+
            '       <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+
            '       <h4><i class="icon fa fa-check"></i> Success!</h4>'+
            '       '+json['success']+''+
            '     </div>'+
            '   </div>'+
            ' </div> ');
       }

       if(json['error']) {

         var html='';
         $.each( json['error'], function( key, value ) {
          html += value+'<br>';
        });
        $('.message_center')
          .html('<div class="row">'+
            '   <div class="col-md-12">'+
            '     <div class="alert alert-warning alert-dismissible">'+
            '       <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+
            '       <h4><i class="icon fa fa-warning"></i> Error! There was a problem.</h4>'+
            '       '+html+''+
            '     </div>'+
            '   </div>'+
            ' </div> ');
       }

    }

   });
});

Solution 2:

You need to prevent the default action of form i.e. submit when input type of submit is clicked, so that your ajax process runs smoothly. In your click event add e.preventDefault();

$('#submit_form').on('click', function (e) {
     //get the e as parameter
     e.preventDefault();
     //rest of your code.
});

Post a Comment for "AJAX-PHP Stay On Same Page If Validation Fails"