Validate a simple HTML form via JSON answere - javascript

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.

Related

Form that already being validated by JS. Need to have it also clear fields on submit

I have a web form that is part of a CMS, therefore I am not able to alter the input field of the submit button. The form is already being validated by JS, so I need to add a line to the existing code below that will clear the fields.
Currently, the page redirects to a Thank you page on submit. I want it to continue doing that. But, currently, if the user hits the back button on their browser, the data is still there. I need it to submit the data, clear the fields, then redirect to the thank you page.
$('form').submit(function(event)
{
if (validateForm())
return true;
event.preventDefault();
});
Have you tried adding document.querySelector('form').reset() above the return statement? In jquery that might just be $(this).reset(), I'm not sure.
if (data.status) {
$(this).find('input').val('');
// code to redirect to success page here
}
If form is successfully sent, then set the value of all inputs in the sent form to a string with the length of 0.
$('form').submit(function(event) {
event.preventDefault();
if (!validateForm()) {
return false;
} else {
formSubmit($(this));
}
}
);
function formSubmit(form) {
var url = form.attr('action');
var method = form.attr('method');
var data = form.serialize();
$.ajax({
method: method
, url: url
, data: data
})
.done(function (data) {
try {
$(this).find('input').val('');
// code to redirect to success page here
} catch (e) {
console.log(e);
}
});
}
FE validation is bad practice in my honest opinion, just good for lowering the amount of HTTP requests to the server. The hard form data validation should happen on the BE.

Determining duplicate values before a form is submitted

Say I have an online form, and I want to figure out whether a user is entering an email that's already in use by the system. Can I tell the system to check the field against the database as soon as the user moves their cursor / selection away from the field? Could anyone point me in the right direction if this is actually possible?
You could attach a listener to the text field using jQuery's blur event, like so:
$('#MyEmailField').blur(function() {
// jQuery AJAX Call here, $.ajax(...)
})
For this You need to call ajax when user writing an email id means on blur event as below :
$('#yourfieldID').blur(function() {
var val = $(this).val();
$.ajax({
type: 'POST',
url: 'your url',
data: {email: val},
success: function (data) {
// check for response
});
}
});
});
Now In file which you called in ajax url, Your need to check data which is exist in database or not and according to that you need to send response and check it in sucess part of ajax call.
I hope you will get it.
Yes, it is possible using an AJAX call on the "onblur" event of Javascript (or "focusout" method of jQuery)
You could use something like this, in the HTML:
<input type="email" name="myinput" />
And the JS:
$( "input" ).focusout(function() {
var usr_email = $(this).value;
$.ajax({
method: "GET",
url: "some.php",
data: { email: usr_email }
}).done(function( response ) {
if(response == "taken"){
$("input").borderColor = "red";
}
});
}
You can check for email's availability through an Ajax call in database on text change or blur event of email textbox. Then notify the user accordingly.
As soon as user moves out of email field, say tab or mouse click, you need to trigger a function to make a Ajax call to your server. The triggering function would be onBlur of email field. Then check If user email exits, get back Ajax response to notify the user.

Form not submitting with AJAX

=====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!

Sending variables from Wordpress Contact Form 7 submission to success page

I am using Contact Form 7 with Wordpress 3.5.
Currently, when a user submits the message, they are redirected to a success page by using the following in the "Additional Settings" field:
on_sent_ok: 'location.replace("http://www.example.org/success-page");'
I want to be able to customise the output of the success-page by using the input from a field, for example:
on_sent_ok: 'location.replace("http://www.example.org/success-page?name=yourname");'
I hoped that by dropping the usual Contact Form 7 shortcodes into the Additional settings, it may have sent the field value with it, but that's not the case.
Can anyone suggest how I can get the field values from contact form 7 into the url, or alternatively send as a $_POST parameter? It may require some javascript to do this, I guess.
This is possible but you need the save the posted data from the contact form to the session and show it there.
Add this to your functions.php
add_action('wpcf7_mail_sent', 'save_cf7_data');
function save_cf7_data($cf)
{
if(session_id() == '') {
session_start();
}
$current_submission = WPCF7_Submission::get_instance();
$_SESSION['cf7_submission'] = $current_submission->get_posted_data();
}
And your success page you just need to print the session var, like:
echo $_SESSION['cf7_submission']['name'];
That's all.
Another option is to use jQuery or Javascript and catch the form on submit.
After the form is caught you can serialize the params and pass them to a custom page to catch them and do things with them.
Example for jQuery:
jQuery(document).ready(function($) {
$('.wpcf7-form').each(function () {
$(this).on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST', // Can also choose GET instead
url: 'forms/getParams',
data: $(this).serialize(),
dataType: "json",
success: function (data) {
$(this)[0].reset(); // Optional in case you want to clear the form on success
},
error: function (data, errorThrown) {
console.log(errorThrown);
}
});
});
});
});
the 'additional settings' code is javascript and thus is running in the context of the browser. this means you can easily access the form data using normal javascript code
e.g. on_sent_ok: 'location.replace("http://www.example.org/success-page?name=" + jQuery("input[name=name]").val());'
i think you should use $_REQUEST['name']; for fetching your post variable on success page.

html5 validate form with required="true" and custom check

What I'm looking for: way to have innate html 5 form validation using the required="true", where if the user clicks the "Submit" button, the first thing that happens is the automatic html 5 validation where it checks to see if "username" is provided by the user. If it's not, then it displays the ugly error bubble.
If it is provided, however, I then have my own custom validation for checking against the db if the username exists. If it does, then return true (allow submission), false otherwise. What's happening: the form is getting submitted. It's like it does not wait for the success callback to return true/false on whether or not it should be submitted.
I hope that's clear enough! Code below:
html:
<form>
<input type="text" required="true" id="username" />
<button type="submit">Submit</button>
</form>
js:
$("form").submit(function() {
$.ajax({
url: 'usernamechecker.php?username=' + $("#username").val(),
success: function(resp) {
if (!resp.UsernameExists) {
return true; // allow form submission
}
return false; // do not allow form submission
}
});
});
You can't return a value through a callback like that. The callback for "success" won't run until the "ajax" call has completed, long after the "submit" handler has already returned.
Instead of that, I'd just do the submit and let it return with an error if there are server-side issues (like "username in use" or whatever). There's no point making two round-trips. If there are no problems, it can just complete the operation and return whatever results page you want.
You need to add "async: false" as a parameter to your ajax call in order to force the call to finish before continuing on with the rest of the code.
$("form").submit(function(event) {
$.ajax({
async: false,
url: 'usernamechecker.php?username=' + $("#username").val(),
timeout: 1000,
success: function(resp) {
if (resp.UsernameExists) {
event.preventDefault(); // do not allow form submission
},
error: function() {
//fall back code when there's an error or timeout
},
});
});

Categories