在PayPal按钮重定向之前完成AJAX调用

时间:2014-05-15 05:28:37

标签: javascript php mysql ajax paypal

我正在使用PayPal按钮,并希望在按钮将用户重定向到PayPal之前,通过AJAX调用(或任何其他有效的方法)将记录插入数据库。

我看过类似的问题/答案,但无法让它们发挥作用。它们要么重定向到PayPal,要么插入数据库记录......但不能同时插入两者。

类似的问题:
Submit form values before paypalPayPal Button submitting a form and triggering an Ajax call at the same time?AJAX request before regular form is being submitted

这是我的表格:

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top" name="paypalform" id="paypalform">
    <input type="hidden" name="cmd" value="_s-xclick">
    <input type="hidden" name="hosted_button_id" value="XXXXXXXXXXXX">
    <button type="submit" class="radius paypal-button" name="submit" alt="PayPal - The safer, easier way to pay online!">Buy Now!
    <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>

这是我的javascript:

$('paypalform').submit(function(e) {
    e.preventDefault();
    e.returnValue = false;
    var $form = $(this);
    $.ajax({
        url: 'ajax.create_sponsorship.php',
        data: 'XXXXXX',
        dataType: 'json',
        context: $form,
        complete: function() {
            this.off('submit');
            this.submit();
        }
    });
});  

PHP文件ajax.create_sponsorship.php返回TRUE(如果插入成功)或FALSE。

使用上面的代码时,broswer会成功重定向到PayPal,但不会将记录插入数据库。

如果我将第一行改为:

$('#paypalform').submit(function(e) {  

基本上,添加# - 然后插入数据库记录,但它不会重定向到PayPal。

1 个答案:

答案 0 :(得分:0)

更新以下代码并尝试:

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top" name="paypalform" id="paypalform">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="XXXXXXXXXXXX">
<button type="submit" class="radius paypal-button prevented" name="submit" id="paypalsubmit" alt="PayPal - The safer, easier way to pay online!">Buy Now!
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>

脚本如下:

<script>
    $(document).ready(function(){
    $('#paypalsubmit').click(function(e) {
    if($(this).hasClass('prevented')){
        e.preventDefault();
        $(this).removeClass('prevented');
        $.post( "ajax.create_sponsorship.php",{ data: 'XXXXXX'}, function( result ) {
            if(result){
                $('#paypalsubmit').click();
                return true;
            }
        });  
    }else{
        $('#paypalform').submit();
        $(this).addClass('prevented');
    }
    });  
    })
</script>

希望这有帮助。

相关问题