Jquery: Submit a form without refreshing - javascript

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

Related

Page is getting Submit Without Refresh Via Otp?

I got this website when I fill the information and try to send the OTP page reload
Here's the website:
https://tunisia.blsspainvisa.com/english/book_appointment.php
After you fill the information and click on (Request verification code) and you will know what I mean
What I tried is:
$(function () {
$('#tunisiaThird').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://tunisia.blsspainvisa.com/book_appointment.php',
data: $('#tunisiaThird').serialize(),
success: function () {
}
});
});
});
I'm only a client, so I'm using Tampermonkey to inject.
You need to read more about jquery ajax post or get method here:
https://api.jquery.com/jQuery.post/
And there are tons of questions here if you search you will find tons of examples
Here is a complete example, which is getting error messages from php part and displaying on html form.
Like this: in php : $error .= 'an error happend'; and ajax $('#result').html(data.error);
to display in html.
<div id="result"></div>
$(document).ready(function(){
$('#tunisiaThird').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"book_appointment.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data.error === 'ok'){
$('#result').html('Successfuly');
$('#tunisiaThird')[0].reset();
setTimeout(function() {
window.location = 'index.php';
}, 1000);
} else {
$('#result').html(data.error);
}
}
});
});
});

How to reload / refresh Stripe Checkout button?

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
}

Google ReCaptcha 2 auto submit

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>

Ajax after ajax request, submit form normal way

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.

AJAX: Submitting a form without refreshing the page

I have a form similar to the following:
<form method="post" action="mail.php" id="myForm">
<input type="text" name="fname">
<input type="text" name="lname">
<input type="text" name="email">
<input type="submit">
</form>
I am new to AJAX and what I am trying to accomplish is when the user clicks the submit button, I would like for the mail.php script to run behind the scenes without refreshing the page.
I tried something like the code below, however, it still seems to submit the form as it did before and not like I need it to (behind the scenes):
$.post('mail.php', $('#myForm').serialize());
If possible, I would like to get help implementing this using AJAX,
Many thanks in advance
You need to prevent the default action (the actual submit).
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('mail.php', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
You haven't provided your full code, but it sounds like the problem is because you are performing the $.post() on submit of the form, but not stopping the default behaviour. Try this:
$('#myForm').submit(function(e) {
e.preventDefault();
$.post('mail.php', $('#myForm').serialize());
});
/**
* it's better to always use the .on(event, context, callback) instead of the .submit(callback) or .click(callback)
* for explanation why, try googling event delegation.
*/
//$("#myForm").on('submit', callback) catches the submit event of the #myForm element and triggers the callbackfunction
$("#myForm").on('submit', function(event, optionalData){
/*
* do ajax logic -> $.post is a shortcut for the basic $.ajax function which would automatically set the method used to being post
* $.get(), $.load(), $.post() are all variations of the basic $.ajax function with parameters predefined like 'method' used in the ajax call (get or post)
* i mostly use the $.ajax function so i'm not to sure extending the $.post example with an addition .error() (as Kristof Claes mentions) function is allowed
*/
//example using post method
$.post('mail.php', $("#myForm").serialize(), function(response){
alert("hey, my ajax call has been complete using the post function and i got the following response:" + response);
})
//example using ajax method
$.ajax({
url:'mail.php',
type:'POST',
data: $("#myForm").serialize(),
dataType: 'json', //expects response to be json format, if it wouldn't be, error function will get triggered
success: function(response){
alert("hey, my ajax call has been complete using the ajax function and i got the following response in json format:" + response);
},
error: function(response){
//as far as i know, this function will only get triggered if there are some request errors (f.e: 404) or if the response is not in the expected format provided by the dataType parameter
alert("something went wrong");
}
})
//preventing the default behavior when the form is submit by
return false;
//or
event.preventDefault();
})
try this:
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
The modern way to do this (which also doesn't require jquery) is to use the fetch API. Older browsers won't support it, but there's a polyfill if that's an issue. For example:
var form = document.getElementById('myForm');
var params = {
method: 'post',
body: new FormData(form),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
};
form.addEventListener('submit', function (e) {
window.fetch('mail.php', params).then(function (response) {
console.log(response.text());
});
e.preventDefault();
});
try this..
<form method="post" action="mail.php" id="myForm" onsubmit="return false;">
OR
add
e.preventDefault(); in your click function
$(#yourselector).click(function(e){
$.post('mail.php', $(this).serialize());
e.preventDefault();
})
You need to prevent default action if you are using input type as submit <input type="submit" name="submit" value="Submit">.
By putting $("form").submit(...) you're attaching the submit handler, this will submit form (this is default action).
If don't want this default action use preventDefault() method.
If you are using other than submit, no need to prevent default.
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'save.asmx/saveData',
dataType: 'json',
contentType:"application/json;charset=utf-8",
data: $('form').serialize(),
async:false,
success: function() {
alert("success");
}
error: function(request,error) {
console.log("error");
}
Take a look at the JQuery Post documentation. It should help you out.

Categories