=====UPDATE AGAIN==== (if anyone cares!)
the solution I posted before stopped working for whatever reason. I included a beforeSend in my ajax request and pasted the portion of my js that validates my form into it. Works like a charm now!
$('#form').on('submit', function(e) {
e.preventDefault(); //prevents page refresh
$.ajax({
type: "post",
beforeSend: function(){ // check that form is complete
},
url: "client_config_send2.php",
data: $(this).serialize(),
success: function(data){
alert('Thank you'); hide_request();window.location = "#top";
}
});
});
EDIT
See my answer below, using 2 .preventDefault!
I have read through many pages / examples of this, but for some reason I can't get it to work on "my" form.
I'm simply trying to submit my form without refreshing the page or opening a new page / tab for the confirmation message.
The form:
<form id="form" name="Configurator" method="post" action="">
.... //Client configures his product, display an image if they choose, and request a quote.
<button id="submit_button" type="submit" name="Submit" >Request</button>
</form>
The client_config_send2.php works, it simply pulls a bunch of parameters from the form (configuration, contact info) and puts it into an email. This part works fine before I try to integrate the ajax.
The JS:
$('form').on('submit', function(e) {
e.preventDefault();
if(!validateForm(this)){
return true;
}
$.ajax({
type: "post",
url: "client_config_send2.php",
data: $(this).serialize(),
done: function(data){
alert("Thank you, we will get back to you shortly");
}
});
})
</script>
The validateForm() function also works, it checks if the configuration is valid, if the email / contact info is complete, etc.
At this point, the validateForm works: if info is missing, the alert pops up. However when validateForm() returns true, the form doesn't submit, nothing happens.
I have tried success instead of done, return false instead of true in the JS, and many other things I found online but I am lost. Never used AJAX before so I'm not 100% confident with the subtleties of the language!
Thanks in advance!
"client_config_send2.php" is a filename. The URL you give to Ajax needs to be, well, a URL like http://example.com/client_config_send2.php.
Change done to success:
success: function(data){
success only fires after your request got response and the response code is OK(http 200).
Update the code below:
$('form').on('submit', function(e) {
e.preventDefault();
if(!validateForm(this)){
return true;
}
var formdata = $(this).serialize();
$.ajax({
type: "post",
url: "http://www.example.com/client_config_send2.php",
data: formdata,
success: function(data){
alert("Thank you, we will get back to you shortly");
}
});
})
</script>
Could you try removing/commenting event.preventDefault();
If this method is called, the default action of the event will not be triggered. (http://api.jquery.com/event.preventdefault/)
Try coding in the following format. The logic uses an if/else statement to make the ajax call.
$('form').on('submit', function(e) {
//If form could not be validated
if(!validateForm(this)){
//prevent the form form submitting
alert("Your form is not valid for submission!");
e.preventDefault();
}
//else
else{
//form input is valid
//make the ajax call
$.ajax({
type: "post",
url: "client_config_send2.php",
data: $(this).serialize(),
done: function(data){
alert("Thank you, we will get back to you shortly");
}
});
}
});
});
Here is the final code that does exactly what I want:
- the validateForm() function works as it should. If the form is not complete, it returns false, an alert pops up and the form does not submit
- if validateForm() returns true, the form gets submitted, the confirmation alert pops up and the page does NOT refresh. Users can then build a new configuration and submit a new request without re-entering all the contact info.
The 2 .preventDefault did the trick!
$('form').on('submit', function(e) {
e.preventDefault(); //prevents page refresh when form is submitted
//If form could not be validated
var x = validateForm();
if(x == false){
//prevent the form form submitting
e.preventDefault();
}
//else
else {
//form input is valid
//make the ajax call
$.ajax({
type: "post",
url: "client_config_send2.php",
data: $(this).serialize(),
success: function(data){
alert('Thank you! we will get back to you within 24 hours. Please check your junk / spam folder if you do not receive a response within that time.');
}
});
}
});
Thanks everyone for your help!
Related
I´am a UX designer and one of these JS dummie/"HTML coder" guys.
I need help or a hint to validate a simple HTML form via a second request which returns a JSON answere, before the form is send.
I have a really simple HTML form on a landingpage where the user can enter a coupon code:
<form id="tokensubmit" method="GET" action="https://www.xyz/cart.html">
<div class="form-group">
<input type="text" name="tokenCodeAdd" id="tokenCodeAdd" size="25" value="" class="form-control input-lg" placeholder="Please enter Coupon Code">
</div>
<input id="input_id" type="submit" class="btn btn-lg btn-warning btn-block" value="Submit">
</form>
If a user enters his Coupon code and hit the submit button, the code will be added to the action URL (https://www.xyz/cart.html) and the User is redirected to this cart.html page. If the coupon code is correct everything is fine. If not he receives an error message on the cart.html page.
So far so good.
BUT: I want to validate the coupon code without redirecting the user to a new website(cart.html).
The system offers a second URL for this already. A url like:
/checkout/validate.html?tokenCode=12345678
This returns a JSON answere with a status like:
{"error":"Wrong Coupon Code."}
if the Coupon code isnt right.
If it is valid, something like:
{"error":"null"}
returns.
What I am searching for is a simple solution to call the validation URL (validation.html) first on click on the "submit" button, parse the returning JSON, prevent the form from sending if "error" is something else than "null" and print the JSON message ("Wrong Coupon Code.") right above the form input.
If "error" = "null" the forms behavior should not change. It should just open the https://www.xyz/cart.html URL with the tokenCode attached as parameter.
What I´am trying/starting with looks like:
$('#tokensubmit').submit(function(event){
event.preventDefault();
var tokenCheck = $(this).find('input[id="tokenCodeAdd"]').val();
$.ajax({
url: '/checkout/validate.html'+tokenCheck,
type: 'GET',
success: function(data){
var jsonData = $.parseJSON(data);
}
});
});
Its just the beginning, I know. The real parsing part is missing and the error message output if the validation fails, or the redirect if not.
Anyone who could help?
And thx in advanced!
Small hint: The form is placed on a WordPress driven landingpage, so PHP and JQuery is an option.
The code you have for getting the validation is almost correct:
$('#tokensubmit').submit(function(event){
event.preventDefault();
var tokenCheck = $(this).find('input[id="tokenCodeAdd"]').val();
$.ajax({
// either attach the parameter like you are trying to do directly to the url,
// but in this way:
url: '/checkout/validate.html?tokenCode='+tokenCheck,
// or give the URL parameter(s) as data object to jQuery:
data: {
tokenCode: tokenCheck
}
type: 'GET',
// if you specify the dataType you want to receive as json,
// jQuery will parse it for you already
dataType: 'json',
success: function(data){
// now you can check the data for error or not, for example like:
if(data.error == null){
// do something (most likely REALLY submit the form now?)
}else{
alert('tokenCode invalid');
}
}
});
});
With jquery you can send through a data parameter and it will work out how to place it in the URL:
$.ajax({
url: '/checkout/validate.html',
type: 'GET',
data: {"tokenCode": tokenCheck}
success: function(data){
var jsonData = $.parseJSON(data);
}
});
I would also advise not doing an Ajax request at all if tokenCheck is empty.
Wouldn 't it be easier to check the coupon code when the user leaves the input field? First the example while submitting the whole form.
$('#tokensubmit').on('submit', function(event) {
event.preventDefault();
var validationSuccess = false;
$.ajax({
url : '/checkout/validate.html',
type : 'GET',
data : { tokenCode : $('#tokeninput').val() }
success : function(response) {
var data = $.parseJSON(response);
if (data.error === null) {
validationSuccess = true;
}
}
if (validationSuccess === true) {
$('#tokensubmit').off('submit').submit();
}
});
So what we 've done here? The submit event listener is nearly the same you 've done. We prevent the default submitting of the form and do an ajax request for validation the input value. If the request returns no error as response, we simply unbind the submit event listener from the form and submit the form again.
In my opinion it would be better to work with the blur event listener on the input field. In combination you could use the HTML5 Constraint Validation API. So you don 't have to submit the form and the ajax request would be done on blurring the input field. I think that would be the better user experience.
So here 's the blur event listener:
<input type="text" name="the-input-field" id="the-input-field" value="" required>
$('#the-input-field').on('blur', function(event) {
var element = this;
$.ajax({
url : '/checkout/validate.html',
type : 'GET',
data : { tokenCode : element.val() }
success : function(response) {
var data = $.parseJSON(response);
if (data.error !== null) {
element.setCustomValidity('Your input is invalid!');
// place some error message elsewhere in the markup
} else {
element.setCustomValidity('');
}
}
});
});
First we placed the required Attribute in the input element. It marks the input element as required. So if it 's empty you could not submit the form. Then we placed the blur event listener, which is doing the ajax request. If the response is false, we place a custom error via setCustomValidity. It is a native HTML5 Constraint Validation API function. If the custom error on the input element is set, you could not submit the form. If the user enters another token the request is done again on leaving the input element. If the token is valid, the custom error message will be removed and the form can be submitted.
I have this issue, which I can't seem to solve..
I've got a form which submits the data to a google sheet.
<form action="https://docs.google.com/sheeturl" method="post" target="hidden_iframe1">
which works perfectly fine (but redirects the user to google forms thank you page).
I tried to prevent this behaviour (I want to load a thank you page on my own domain) and added the following onsubmit event
onsubmit="window.location.href = 'http://thankyoupage.html';"
which by itself doesn't change anything. So I added
return false;
Now the redirect works fine (loading my thank you page), however the form data is not being submitted to the sheet.
I am pretty sure there's a banal and easy solution for this, but I am just lacking the knowledge to solve it.
Thanks.
By setting a return false you are basically hijacking the functionality of the form - it's not posting to google at all like that. Try submitting the form using AJAX. With jQuery it could be done like this:
$("#ajaxForm").submit(function (e) {
e.preventDefault();
$.ajax({
url: "https://docs.google.com/forms/d/FORMKEY/formResponse",
beforeSend: function (xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', 'chrome-extension://EXTENSION_ID');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PUT');
},
data: JSON.stringify($(this).serializeArray()),
type: "POST",
dataType: "xml",
xhrFields: {
withCredentials: true
},
statusCode: {
0: function () {
document.getElementById("message").innerHTML = "Your form has been submitted!";
window.location.replace("http://thankyoupage.html");
},
200: function () {
document.getElementById("message").innerHTML = "Your form has been submitted!";
console.log("Success");
window.location.replace("ThankYou.html");
}
}
});
});
I've got some jquery that submits a form for me. It works just fine. The only major problem is how simple it is.
The form submits the info to the database using my php script without refreshing the page, but the page isn't updated in any way to show the new data. What are some good ways to update the page or div so my new data is displayed after submitting the form. Below is my code
$(function() {
$('#form').submit(function(e) {
var data = $(this).serialize();
// Stop the form actually posting
e.preventDefault();
// Send the request
$.ajax({
type: "POST",
url: "submit.php",
data: data,
cache: false,
success: function(html){
$('textarea#joke').val('');
}
});
});
});
You are very close, just use html() method or text() depend on your needs, for your example I think text is better, since you want put text into textarea
success: function(html){
$('textarea#joke').text(html);
}
but if you want put some html into custom div do
success: function(html){
$('#custom-div').html(html);
}
Suppose from the submit.php, you are returning some value as status = true if form submitted suceessfully else status = false
then in your ajax code, you can use it as
success: function(html){
if(html.status == true)
$('textarea#joke').html('Form submitted succcessfully');
else
$('textarea#joke').html('ERROR!');
}
OR
success: function(html){
$('textarea#joke').val(html.status);
}
This would update the div content of $('textarea#joke')
Hope this would help you.
Thanks.
The server is written in web2py, and hosted on google app engine. I can visit my index.html by entering domain.com/index and I can send form by entering domain.com/register where "register" is a function defined by default.py
However, in html, where I would like to send form to the server and get a response, I use ajax which has cross domain issues. So I use "register" as URL, and it does not work. Help?
$("#signup").click(function() {
$.ajax({
type: "POST",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
By typing domain.com/register, I can totally trigger the function. What is the problem here? And the form is sent to domain.com... In browser it appears as htt[://domain.com/?email=ada#ad.com&password=adsa
Its very possible register is looking for GET instead of POST
try changing the type in ajax
$("#signup").click(function() {
$.ajax({
type: "GET",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
I found, on this site a way to submit a POST form without leaving the page. In that script, they put instructions on how to have a function take place after the form's been submitted. Here's what the script looked like:
$(document).ready(function(){
$form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
},'json');
return false;
});
});
They said, between function(response){ and },'json'); you can specify other JavaScript to take place like alerts etc. after the form's been submitted. I tried
$(document).ready(function(){
$form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
$('form').hide();
},'json');
return false;
});
});
Unfortunately, that does not work, can anybody tell me why? I've set up a jsFiddle. Please help. Thanks.
Using $.post, the "function(response)" is only called AFTER a successful result, so you have been misinformed about doing work within this function while the server is processing the request.
To continue processing after sending the request to the server, place the $('form').hide() after the $.post call:
$form.submit(function(){
$.post(
$(this).attr('action'), $(this).serialize(),
function(response){
}
,'json'
);
$('form').hide();
return false;
});
Problems:
Set JavaScript variable as form, not $form. Then use it in jQuery as $(form).
The context of $(this).attr('action') is the $.post() callback, not the form. Solution: $(form) instead of $(this).
Solution:
$(document).ready(function(){
form = $('form');
$(form).on('submit', function() {
$.post($(form).attr('action'), $(this).serialize(), function(response) {
$('form').hide();
},'json');
return false;
});
});
Your fiddle worked fine when the form is changed to
<form action="#" method="post">
And the documentation at http://api.jquery.com/jQuery.post/ shows that this is a valid syntax and http://www.johnnycode.com/blog/2010/04/08/jquery-form-serialize-doesnt-post-submit-and-button-values-duh/ is also a running sample. If it's not working at all for you then, as silly as this is, do you have a reference to jQuery in your page?