jQuery AjaxForm plugin have to submit twice

396 views Asked by At

I am trying to use the ajaxForm plugin to submit a form via ajax. The problem I am having is that I need to submit the form twice to actually get the form to submit. See code below, and I appreciate any help.

$(document).on('click', 'button.submit-btn', function () {
    alert('Please wait...');
    setTimeout(function() {
    $('button.submit-btn').attr('disabled', true);
    }, 50)
    $('#send-form').ajaxForm(function() { 
      var currentAlert = $.jAlert('current');
      currentAlert.closeAlert();
      successAlert('Success!', 'The form has been submitted');
      $('button.submit-btn').attr('disabled', false);
    }); 
});

 <form action="" method="post" id="send-form">
     <button type="submit" class="submit-btn" name="send-modal-form" value="submit"></button>
 </form>

I tried to change it to ajaxSubmit and then add e.preventDefault(); but then the form doesn't submit at all when I try.

1

There are 1 answers

7
Emiliano On

In your code you have severals errors

1) the submit button and try ajax submit

use type button or a link when you click a submit button the browser try to send the form automatically and you are running a js but that's not prevent submit

2) use alert instead jAlert

change alert to jAlert

3) this code initialize the observer that execute the ajax

 $('#send-form').ajaxForm(function() { 
      var currentAlert = $.jAlert('current');
      currentAlert.closeAlert();
      successAlert('Success!', 'The form has been submitted');
      $('button.submit-btn').attr('disabled', false);
    }); 

then you add it on click but you must add it on document load so here are the code

$( document ).ready(function() {

    $('#send-form').ajaxForm(function() { 
      var currentAlert = $.jAlert('current');
      currentAlert.closeAlert();
      successAlert('Success!', 'The form has been submitted');
      $('button.submit-btn').attr('disabled', false);
    }); 
});

$(document).on('click', 'input.submit-btn', function () {
    jAlert('Please wait...','Please wait...');
    setTimeout(function() {
    $('button.submit-btn').attr('disabled', true);
    }, 50)
});

here is the HTML

 <form action="" method="post" id="send-form">
     <input type="button" class="submit-btn" name="send-modal-form" value="submit" />
 </form>