ajaxformsjqueryajax-forms

Sending AJAX request before submitting the form


Problem: I'm trying to send ajax reguest, and then submit the form.

Aproaches: 1. I solved the problem by putting

success: function() { 
   document.myform.submit();
}

But i think it's not the most elegant solution. Can you explain me why it works only if i put document.myform.submit(); in success? Is there any other way to solve this problem?

<div class="buttons">
  <div class="right">
        <form name="myform" onsubmit="javascript: startAjax(); return false;" action="https://example.com/payment.php" method="get">
                    <input type="hidden" name="merchantId" value="<?php echo $merchantIdKZM; ?>"> 
                    <input type="submit" value="<?php echo $button_confirm; ?>" id="button-confirm2" class="button" name="PayKZM" />
                </form>
    </div>
</div>

<script type="text/javascript">
function startAjax() {
    console.log("dafaaaa");
    $.ajax({ 
                type: 'get',
                url: 'index.php?route=payment/bank_transfer/confirm',
                async: 'false',
                success: function() {

                        // location = '<?php echo $continue; ?>';
                }               
        });

} // Calls ajaxComplete() when finished

function ajaxComplete()
{
    console.log("dafa");
  document.myform.submit();
}
</script>

Solution

  • success's function is called upon the get request receiving a valid response as @harsh pointed out. Thus it will occur after the get request. I believe something similar to the following would do as you request though I haven't tested it:

    <script type="text/javascript">
    $(function () {
        $("#form").on('submit', function () {
            var $form = $(this);
            $.ajax({
                type: 'GET',
                url: 'index.php?route=payment/bank_transfer/confirm',
                data: $form.serialize(),
                async: 'false',
                success: function () {
                    $.ajax({
                        type: 'GET',
                        url: 'https://example.com/payment.php',
                        data: $form.serialize(),
                    });
                }
    
            });
        });
    });
    </script>