I have a PayPal button which submits a form to the url specified int the form's action=""
attribute. What I would like this button to do is trigger an ajax call at the same time (or roughly the same) with submitting the form.
So the form looks like this:
<?php echo('
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="payWithPayPalForm">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="me@mydomain.com">
<input type="hidden" name="amount" value="'.$price.'">
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHostedGuest" >
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_paynowCC_LG.gif" border="0" id="payWithPayPalButton" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/pl_PL/i/scr/pixel.gif" width="1" height="1">
</form>
');
?>
And the ajax request is following:
$.ajax({
type: "POST",
url: "classes/acceptOfferFunction.php",
data: {
hash: getURLParameter('hash'),
hash2: getURLParameter('hash2')
},
success: function (result) {
}
});
The problem here, is that your ajax request will be cancelled because the page will reloaded (in fact redirected to paypal).
What you can do, is to send the ajax request when your submit the form and wait until the ajax request finish. Then, send the form.
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" onsubmit="return ajaxRequest()" method="post" id="payWithPayPalForm">
Using onsubmit
, when user will send the form, the function ajaxRequest
will be fired. Since we put a return before, form will wait for the return of the function to continue.
ajaxRequest()
return true, the form will be submitted.This is POC. You have better way to handle that in a non-obstructive way (using jQuery on the form id for example). And you will have to code the function too.