Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax submit after parsley.js validation

I have a form that submits through ajax. Works fine. However, I am trying to work out how to ONLY submit it if parsley successfully verifies the form.

The issue is that the form submits even if parsley displays an issue. How can I allow for this?

<script>
  $(document).ready(function(){
  $('#newsletterSubscribe').on('submit',function(e) {

  $.ajax({
    url:'scripts/newsletter.php',
    data:$(this).serialize(),
    type:'POST',
    success:function(data){
    console.log(data);
    $("#success").show().fadeOut(20000); //=== Show Success Message==
    },
    error:function(data){
    $("#error").show().fadeOut(20000); //===Show Error Message====
    }
  }); 
  e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
  });
  });
</script> 
like image 367
Alex Avatar asked Feb 11 '23 08:02

Alex


1 Answers

You need to add the Parsley validation condition, as following:

<script>
  $(document).ready(function(){
  $('#newsletterSubscribe').on('submit',function(e) {
  e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
  if ( $(this).parsley().isValid() ) {
     $.ajax({
       url:'scripts/newsletter.php',
       data:$(this).serialize(),
       type:'POST',
       success:function(data){
       console.log(data);
         $("#success").show().fadeOut(20000); //=== Show Success Message==
       },
       error:function(data){
         $("#error").show().fadeOut(20000); //===Show Error Message====
       }
     }); 
   }
  });
  });
</script> 

Note also that the Prevent Default behavior is set as a first step in the process.

like image 149
Yazid Erman Avatar answered Feb 13 '23 20:02

Yazid Erman