Reputation: 101
I try to send a confirm post with the sendPostAjax()
function after the form send_button have been clicked and then submit the form to payment provider. But I get the sendPostAjax()
function executed on page load, before the click is made.
I have tried to put the sendPostAjax()
function inside the click catching, but then the promise can not be assigned as the sendPostAjax() function is undefined.
Any suggestions how I should solve this?
HTML FORM
<form id="payment" method="post" action="https://my-payment-provider.com">
<input type="hidden" name="charset" value="utf-8">
// --- additional data here
<button type="submit" name="submit" id="send_button">PAY</button>
</form>
JAVASCRIPT CODE
<script type = "text/javascript">
// Get click and call sendPostAjax function
document.getElementById('send_button').addEventListener('click', function () {
sendPostAjax();
return false;
});
function sendPostAjax() {
return $.ajax({
url: 'confirm.php',
type: 'POST',
data: {
cid: '9999999'
}
});
}
// function that expects a promise as an argument:
function sendForm(x) {
x.success(function () {
$('#payment').submit;
});
}
// get a promise from sendPostAjax:
var promise = sendPostAjax();
// give a promise to other function:
sendForm(promise);
</script>
Upvotes: 2
Views: 6398
Reputation: 6612
You can do this using jQuery
button click handler, replace your code with below and try:
Updated code (form submission after ajax success
):
$('#send_button').click(function() {
var form = $('#payment');
if (form.attr('confirm') === undefined) {
$.ajax({
url: 'confirm.php',
type: 'POST',
data: {
cid: '9999999'
},
success: function(data) {
form.attr('confirm', '1');
$('#send_button').click();
}
});
return false;
}
return true;
});
Upvotes: 1
Reputation: 3453
This should do it...put it right after you have defined both functions
$('#send_button').click(function() {
// get a promise from sendPostAjax:
var promise = sendPostAjax();
// give a promise to other function:
sendForm(promise);
});
Upvotes: 0