2013-04-21 90 views
0

問題:我正在嘗試發送ajax請求,然後提交表單。在提交表單之前發送AJAX請求

Aproaches: 1.我通過把

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

解決了這個問題但我認爲這不是最完美的解決方案。你能解釋一下爲什麼只有當我把document.myform.submit(); in success?有沒有其他辦法可以解決這個問題?

<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> 
+0

堂妹'當您收到從我不在服務器 – shashwat 2013-04-21 07:50:12

+1

您請求的有效響應success'函數被調用看看爲什麼在成功功能中使用該代碼不是一個好的解決方案。你是否總是提交表單,或者你是否試圖從AJAX的響應中檢查某些內容? – user1048676 2013-04-21 07:51:25

+0

我總是提交表單。 – max 2013-04-21 17:19:07

回答

1

成功的函數在獲取請求接收到@harsh指出的有效響應時被調用。因此它會在獲取請求之後發生。我相信,雖然我沒有測試它作爲您的要求類似於下面的東西會做:

<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>