简体   繁体   English

在提交表单之前发送AJAX请求

[英]Sending AJAX request before submitting the form

Problem: I'm trying to send ajax reguest, and then submit the form. 问题:我正在尝试发送ajax请求,然后提交表单。

Aproaches: 1. I solved the problem by putting 方法:1.我解决了问题

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 您能解释一下为什么只有在我放置document.myform.submit(); in success它才起作用吗document.myform.submit(); in success document.myform.submit(); in success ? 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>

success's function is called upon the get request receiving a valid response as @harsh pointed out. 如@harsh所指出的,在get请求收到有效响应后,调用成功函数。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM