Question

I have a form which when submitted checks if Account Number is valid(through AJAX).

If invalid, it shows error message. This is working fine.

If valid, it should submit the form. It submits but only after clicking Submit button twice.

$('#account_validation_form').on('submit', function(e){

    e.preventDefault();

    var payers_account = $("input[name='payers_account']").val();

  $.post('ajax.php', {payers_account:payers_account}, function(data){

  if(data === 'invalid'){
     $(".account_invalid_message").html("<p>Given Account Number is invalid</p>");
  }

  else if(data === 'valid'){
     $("#account_validation_form").unbind('submit').submit()
  }

  });

});

I know something is wrong with calling e.preventDefault() there. But it is necessary and it can't be put inside AJAX Callback. So What would be the solution for this ?

Was it helpful?

Solution

$('#submit_button_id').on('click', function(e)
{
    var payers_account = $("input[name='payers_account']").val();
    $.post('ajax.php',
    {
        payment_amount: payment_amount,
        payers_account: payers_account,
    }, function(data)
    {
        if (data === 'invalid')
        {
            $(".account_invalid_message").html("<p>Given Account Number is invalid</p>");
        }
        else if (data === 'valid')
        {
            $("#account_validation_form").submit();
        }
    });
});

use this code and do a little change on HTML change the type="submit" to type="button" for your submit button

OTHER TIPS

Try binding the form post to submit button click event: ie:

$('#submit_button_id').on('click', function(e){



    var payers_account = $("input[name='payers_account']").val();

  $.post('ajax.php', {payment_amount:payment_amount, payers_account:payers_account,}, function(data){

  if(data === 'invalid'){
     $(".account_invalid_message").html("<p>Given Account Number is invalid</p>");
  }

  else if(data === 'valid'){
     $("#account_validation_form").submit();
  }

  });

}); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top