I'm submitting my Stripe Checkout form via AJAX (catching the form submit event) because I have a complex multi-pane HTML form and want to display payment errors from Stripe without having to reload the page and regenerate the form or making the user re-enter a load of info.
This all works fine, except once the Stripe Checkout button is used once it's disabled. After I display the error message on the booking form page, I need the user to be able to click the Stripe button again and try different payment info.
How do I reactivate the Stripe button? Do I need to remove the whole Stripe button script from the DOM (I'm using jQuery) and re-insert it (or similar code) fresh?
My standard Checkout button code:
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="my_stripe_key"
data-image="mylogo.png"
data-name="My Booking Form"
data-zip-code="true"
data-locale="auto"
data-email=""
data-description="Payment for this booking"
data-currency="gbp"
data-amount=""
data-label="Pay and book!">
</script>
and if relevant, my AJAX form submit code:
$('#booking-form').get(0).submit = function() {
var formdata = $(this).serialize();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('#booking-form > input[name="_token"]').val()
},
type: 'POST',
url: 'book',
dataType: 'json',
data: formdata,
success: function(data) {
if (data.response == 'ok') // Payment went through OK
{
// Redirect to booking confirmation page:
window.location.replace(data.url);
} else // Payment failed, alert user to try again
{
$('#erroralert').text('Sorry, payment failed, please try again').removeClass('nodisplay');
}
},
error: function(data) // Server error
{
console.log('Error:', data.responseText);
}
});
// Prevent form submit.
return false;
}
You have an attribute disabled="true" which is set to the submit button element after the form is submitted. You just need to remove this attribute : $('button[type="submit"]').get(0).removeAttr("disabled");.
Example that works :
http://jsfiddle.net/5xq8Lhda
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="booking" action="your-server-side-code" method="POST">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_TYooMQauvdEDq54NiTphI7jx" data-amount="999" data-name="Stripe.com" data-description="Widget" data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto" data-zip-code="true">
</script>
</form>
<script>
$('#booking').get(0).submit = function() {
$('button[type="submit"]').get(0).removeAttr("disabled");
return false;
}
</script>
To use your example, you should do something like that :
$('#booking-form').get(0).submit = function() {
var formdata = $(this).serialize();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('#booking-form > input[name="_token"]').val()
},
type: 'POST',
url: 'book',
dataType: 'json',
data: formdata,
success: function(data) {
if (data.response == 'ok') // Payment went through OK
{
// Redirect to booking confirmation page:
window.location.replace(data.url);
} else // Payment failed, alert user to try again
{
$('#erroralert').text('Sorry, payment failed, please try again').removeClass('nodisplay');
$('button[type="submit"]').get(0).removeAttr("disabled");
}
},
error: function(data) // Server error
{
console.log('Error:', data.responseText);
}
});
// Prevent form submit.
return false;
}
If you intend to submit your form by AJAX, or just generally want more control over the checkout experience, I'd recommend using the Custom Checkout integration here.
Simple Checkout was designed around a very straight-forward use case: fill out the form, complete a simple form submit. You can do things like attempt to grab the submit button and remove the disabled attribute, though Stripe could always change things up, it may not act as you intend.
The Custom integration provides a perfect place for your ajax submit or additional js code, in the token callback,
token: function(token) {
// your form submission or next steps here
}
Related
I have a form calling submitting as follow
<form action="" method="post" id="member_form" onsubmit="return json_add('member','<?php echo ($admin->getnew_id()); ?>','0','slider_form');">
The problem I have is to get the $new_id before submitting the form from another function class.
this is not working
It keep running the funtion getnew_id() and generate the ID before it is saved
I need the process as follow.
Form Open
User complete form
onsubmit it need to do follow.
a. get new id = $new_d
b. then do
return json_add('member','','0','slider_form');">
I tried the following but dont work
$("form").submit(function(){
$.ajax({
url:"lastid.php",
type:'POST',
success:function(response) {
var $new_id = $.trim(response);
return json_add('member-add',$new_id,'0','slider_form');
alert("Submitted");
}
});
The problem seems to be in the third step.
What you should do is prevent the form from submitting and handle it in ajax.
you need onsubmit="return false" to prevent the form from submitting
Next, handle the submission in ajax
$("form#member_form").submit(function(){
$.ajax({
url: "lastid.php",
type: "POST",
data: { // this is where your form's datas are
"json": json_add('member-add',$new_id,'0','slider_form'),
"key": $("form#member_form").serialize()
},
success: function(response) {
var $new_id = $.trim(response);
alert("Submitted");
// alerting here makes more sense
}
// return json_add('member-add',$new_id,'0','slider_form');
// returning here do nothing!
});
You can read more about using ajax in jQuery here
Im trying to submit a form like this way:
<form id="myForm" action="http://example.com/somefile" method="POST">
...
...
...
<input type="submit" id="sendForm" value="send">
</form>
the action link its a webservice developed by another developer, so, when i submit the form, the webservice replies me with an URL (http://www.example.com/thanks), what i wanna do is to avoid this webservice reply, and in place, change the url of the redirect, is this possible?
Ive tried too do it with:
<script>
$("#sendForm").click(function () {
if (form_check_validation()) {
$("#myForm").submit();
window.location.replace("http://stackoverflow.com");
} else {
return false;
// event.preventDefault();
}
});
</script>
But its not working.
Thanks
NOTE: The webservice is in another server, so im having issues with cross-domain origin.
https://api.jquery.com/event.preventdefault/ Google is your friend, bud...........
Assuming this service allows cross origin and you don't want / need to move to a different page, why not use ajax?
You can simply create and ajax call using $.ajax.
see http://api.jquery.com/jquery.ajax/
Example:
$.ajax({
url : "POST_URL",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
// Handle server response
},
error: function (jqXHR, textStatus, errorThrown)
{
// Handle error
}
});
You can do it with Ajax. I also recommend that you bind a submit event listener to the form so that the submission works correctly also when pressing Enter.
$("#myForm").submit(function (event) {
if (form_check_validation()) {
form_submit(this);
} else {
// ...
}
event.preventDefault();
});
function form_submit (form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize()
});
}
My users will see a google repcatcha2 (nocaptcha) in a web page. When they solve the captcha (put the tick in the box) the form should be automatically submit.
Is there any way to do that?
Sure you can do it.
In this post I've explained how to insert reCaptcha into a site and to code javascript to verify user and site.
Add a name to your form with reCaptcha: <form method="post" name="myform">
Add document.myform.submit(); code for submitting of the form upon the site verification success event:
<script type='text/javascript'>
var onReturnCallback = function(response) {
var url='proxy.php?url=' + 'https://www.google.com/recaptcha/api/siteverify';
$.ajax({ 'url' : url,
dataType: 'json',
data: { response: response},
success: function( data ) {
var res = data.success.toString();
if (res)
{ document.myform.submit(); }
} // end success
}); // end $.ajax
}; // end onReturnCallback
</script>
I have ajax request:
<script>
$("#abc_form_submit").click(function(e) {
e.preventDefault();
//........
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $("#abc_form").serialize(), // serializes the form's elements.
success: function(data)
{
if(data.success == 'false') {
// show errors
} else {
// SUBMIT NORMAL WAY. $("#abc_from").submit() doesnt work.
}
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
And php
.....
return $this->paypalController(params, etc...) // which should redirect to other page
.....
How should i make that ajax request if success, submit form normal way, because now if I redirect (at PHP) its only return response, but i need that this ajax request would handle php code as normal form submit (if success)
Dont suggest "window.location" please.
I would add a class to the form to test if your ajax has already occured. if it has just use the normal click funciton.
Something like:
$('form .submit').click(function(e) {
if (!$('form').hasClass('validated'))
{
e.preventDefault();
//Your code here
$.post(url, values, function(data) {
if (success)
{
$('form').addClass('validated');
$('form .submit').click();
}
});
}
}
Why don't you use a result variable that you update after a succesful AJAX request?
<script>
$("#abc_form_submit").click(function(e) {
e.preventDefault();
// avoid to execute the actual submit of the form if not succeded
var result = false;
//........
$.ajax({
type: "POST",
url: url,
dataType: 'json',
async: false,
data: $("#abc_form").serialize(), // serializes the form's elements.
success: function(data)
{
if(data.success == 'false') {
// show errors
} else {
// SUBMIT NORMAL WAY. $("#abc_from").submit() doesnt work.
result = true;
}
}
});
return result;
});
</script>
I've had this issue before where I needed the form to submit to two places, one for tracking and another to the actual form action.
It only worked by submitting it programatically when you put the form.submit() behind a setTimeout. 500ms seems to have done the trick for me. I'm not sure why browsers have trouble submitting the form programatically when they are attempting to submit them traditionally, but this seems to sort it out.
setTimeout(function(){ $("#abc_from").submit(); }, 500);
One thing to keep in mind though once it submits, that's it for the page, it's gone. If you still want whatever processes are running on the page to run, you will need to set the target of the form to _blank so that it will submit in a new tab.
I have a simple page that takes a form and makes a jsonp ajax request and formats the response and displays it on the page, this is all fine, but I wanted to add it so that if the form was populated (via php $_GET variables) then the form would auto-submit on page load but what happens instead is that the page constantly refreshes despite the submit function returning false.
Submit Button (just to show it doesn't have an id like submit or anything)
<button type="submit" id="check" class="btn btn-success">Check</button>
jQuery
$(document).ready(function() {
$('#my_form').on('submit', function() {
var valid = 1;
$('#my_form .required').each(function() {
if ($(this).val() == '') {
$(this).parents('.form-group').addClass('has-error');
valid = 0;
} else {
$(this).parents('.form-group').removeClass('has-error');
}
});
if (valid === 1) {
$.ajax({
url: '/some_url',
data: $('#my_form').serialize(),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function(data) {
var html = 'do something with data';
$('#results').html(html);
},
error: function() {
$('#results').html('An error occurred, please try again');
}
});
} else {
$('#results').html('Please fill in all required fields');
}
return false;
});
});
The part I added just after the $(document).ready(function(){ and before the submit was:
if ($('#input_1').val() != '' || $('#input_2').val() != '') {
// $('#check').trigger('click');
$('#my_form').submit();
}
Both those lines have the same effect but I am doing the same in another project and it works fine, as far as I can see, the only difference is the jQuery version, I'm using 1.11 for this page.
Update
Apologies, I seem to have answered my own question, I thought that since the programmatic submit was the first thing in $(document).ready(function(){ then maybe it was the case that the actual submit function wasn't being reached before the event was triggered so I simply moved that block after the submitfunction and it now works fine.
url: ''
it seems like you are sending your ajax request to nothing.
just an additional: if you want to submit your form through jquery without using AJAX, try
$("#myForm").submit();
it will send your form to the action attribute of the form, then redirect the page there.