Complete AJAX call before PayPal button redirects

2019-08-18 17:23发布

问题:

I am using PayPal buttons and would like to insert a record into the database via an AJAX call (or any other method that works) before the button redirects the user to PayPal.

I have looked at similar questions/answers but can't get them to work. They either redirect to PayPal or insert a database record...but not both.

Similiar questions:
Submit form values before paypal, PayPal Button submitting a form and triggering an Ajax call at the same time?, AJAX request before regular form is being submitted

This is my form:

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

This is my 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();
        }
    });
});  

The PHP file, ajax.create_sponsorship.php, return either TRUE (if insert was successful) or FALSE.

When using the code above the broswer successfully redirects to PayPal but does not insert record into database.

If I change the first line to this:

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

Basically, adding the # - then the database record gets inserted but it doesn't redirect to PayPal.

回答1:

Update the code as below and try:

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

And script goes as below:

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

Hope this helps.