简体   繁体   中英

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> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM