4

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> 
Alex
  • 51
  • 1
  • 4
  • This might help http://stackoverflow.com/a/15739186/3008050 – karan3112 Dec 16 '14 at 08:48
  • @karan3112 yes i saw this. I tried to put the whole AJAX call inside the if ( $(this).parsley().isValid() ) but it made the page refresh on form submission. – Alex Dec 16 '14 at 08:49
  • 1
    So I think that should be your question. Edit your question with your `parsley` code. – karan3112 Dec 16 '14 at 08:53
  • As @karan3112 said, include the javascript where you are checking for Parsley errors before the ajax call. As it is, it won't work. In case you have your code like the answer in the link above and it still doesn't work, you'll need to check for javascript errors. – Luís Cruz Dec 16 '14 at 13:30

1 Answers1

8

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.

Yazid Erman
  • 1,166
  • 1
  • 13
  • 24