Cymbal Cymbal - 7 days ago 4
jQuery Question

onsubmit event doesn't always work

The following code will work in all my tests and works most of the time but it will not fire for all visitors.

jQuery(document).ready(function(){
jQuery('#formane').on('submit', function(){
jQuery.post('/storeit.php', jQuery(this).serialize(), function(){
console.log('success');
}).fail(function(){
console.log('error');
});
});
});


The storit.php page takes the data and tosses it into a database before the form posts to salesforce. I've tried removing jQuery completely, using onsubmit with a javascript function.

I get about 15% of form posts that just don't fire the code. They range in browser, OS and device.

Answer

You should disable the normal form submission, because when it reloads the page it will cancel the AJAX request. Instead, submit the form in the success function.

jQuery(document).ready(function(){
  jQuery('#formane').on('submit', function(e){
    e.preventDefault();
    jQuery.post('/storeit.php', jQuery(this).serialize(), function(){
      console.log('success');
      $("#formane")[0].submit();
    }).fail(function(){
      console.log('error');
    });
  });
});