HTML5 required attribute not working with AJAX submission - javascript

I am trying to do some basic validation for a simple newsletter form I have that only requires an email. The way I have this form/input within the page, there really isn't room to add any jQuery validate error messages, so I was trying to add a simple HTML 5 required attribute, but the form submits regardless if blank.
What would be the best way to add some simple validation to this so the form checks for an email address, it is filled in, and min length of 4 characters?
<form action="" method="POST" id="newsletter-form">
<input type="email" id="footer-grid1-newsletter-input" placeholder="Your Email Address" required>
<input type="submit" id="footer-grid1-newsletter-submit" name="submit" value='&nbsp'>
</form>
$("#footer-grid1-newsletter-submit").on("click", function (event) {
event.preventDefault();
var newsletter_email = $("#footer-grid1-newsletter-input").val();
var targeted_popup_class = jQuery(this).attr('data-popup-open');
$.ajax({
url: "newsletterSend.php",
type: "POST",
data: {
"newsletter_email": newsletter_email
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to insert email!");
alert(data);
} else {
$("#newsletter-form")[0].reset();
$('.newsletter-popup').fadeIn(350).delay(2000).fadeOut();
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});

The reason is because the validation is done on the submit event of the form, yet you have hooked your event to the click of the submit button. Try this:
$("#newsletter-form").on("submit", function (event) {
event.preventDefault();
// your code...
});
Working example
With regard to validating a minimum input length, you can use the pattern attribute:
<input type="email" id="footer-grid1-newsletter-input" placeholder="Your Email Address" pattern=".{3,}" required>

Related

JS eventListener disable the Form required attribute [duplicate]

This should be simple, yet it's driving me crazy. I have an html5 form that I am submitting with ajax. If you enter an invalid value, there is a popup response that tells you so. How can I check that the entries are valid before I run my ajax submit?
form:
<form id="contactForm" onsubmit="return false;">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required placeholder="Name" />
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" required placeholder="Subject" />
<label for="email">Email:</label>
<input type="email" name="email" id="email" required placeholder="email#example.com" />
<label for="message">Message:</label>
<textarea name="message" id="message" required></textarea>
<input type="submit" id="submit"/>
</form>
submit:
$('#submit').click(function(){
var name = $("input#name").val();
var subject = $("input#subject").val();
var email = $("input#email").val();
var message = $("input#message").val();
var dataString = 'email=' + email + '&message=' + message + '&subject=' + subject + '&name=' + name ;
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: dataString,
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
If you bind to the submit event instead of click it will only fire if it passes the HTML5 validation.
It is best practice to cache your jQuery selectors in variables if you use it multiple times so you don't have to navigate the DOM each time you access an element. jQuery also provides a .serialize() function that will handle the form data parsing for you.
var $contactForm = $('#contactForm');
$contactForm.on('submit', function(ev){
ev.preventDefault();
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: $contactForm.serialize(),
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
By default, jQuery doesn't know anything about the HTML5 validation, so you'd have to do something like:
$('#submit').click(function(){
if($("form")[0].checkValidity()) {
//your form execution code
}else console.log("invalid form");
});
If you are using HTML5 form validation you'll have to send the ajax request in the form's submit handler. The submit handler will only trigger if the form validates. What you're using is a button click handler which will always trigger because it has no association with form validation. NOTE: not all browsers support html5 form validation.
I prefer using the jQuery submit handler, you will still get the response to your form with the following method.
jQuery('#contactForm').on('submit', function (e) {
if (document.getElementById("contactForm").checkValidity()) {
e.preventDefault();
jQuery.ajax({
url: '/some/url',
method: 'POST',
data: jQuery('#contactForm').serialize(),
success: function (response) {
//do stuff with response
}
})
}
return true;
});
Not exactly sure what you mean. But I assume that you want to check in realtime if the input is valid. If so you should use .keyup instead of .click event, because this would lead to an action if the user presses submit. Look at http://api.jquery.com/keyup/
With this you could check the input with every new character insert and display e.g. "not valid" until your validation ist true.
I hope this answers your question!
U can also use jquery validate method to validate form like
$("#form id").validate();
which return boolean value based on form validation & also u can see the error in log using errorList method.
for use above functionality u must include jquery.validate.js file in your script

HTML 5 Validation and call function javascript [duplicate]

This should be simple, yet it's driving me crazy. I have an html5 form that I am submitting with ajax. If you enter an invalid value, there is a popup response that tells you so. How can I check that the entries are valid before I run my ajax submit?
form:
<form id="contactForm" onsubmit="return false;">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required placeholder="Name" />
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" required placeholder="Subject" />
<label for="email">Email:</label>
<input type="email" name="email" id="email" required placeholder="email#example.com" />
<label for="message">Message:</label>
<textarea name="message" id="message" required></textarea>
<input type="submit" id="submit"/>
</form>
submit:
$('#submit').click(function(){
var name = $("input#name").val();
var subject = $("input#subject").val();
var email = $("input#email").val();
var message = $("input#message").val();
var dataString = 'email=' + email + '&message=' + message + '&subject=' + subject + '&name=' + name ;
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: dataString,
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
If you bind to the submit event instead of click it will only fire if it passes the HTML5 validation.
It is best practice to cache your jQuery selectors in variables if you use it multiple times so you don't have to navigate the DOM each time you access an element. jQuery also provides a .serialize() function that will handle the form data parsing for you.
var $contactForm = $('#contactForm');
$contactForm.on('submit', function(ev){
ev.preventDefault();
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: $contactForm.serialize(),
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
By default, jQuery doesn't know anything about the HTML5 validation, so you'd have to do something like:
$('#submit').click(function(){
if($("form")[0].checkValidity()) {
//your form execution code
}else console.log("invalid form");
});
If you are using HTML5 form validation you'll have to send the ajax request in the form's submit handler. The submit handler will only trigger if the form validates. What you're using is a button click handler which will always trigger because it has no association with form validation. NOTE: not all browsers support html5 form validation.
I prefer using the jQuery submit handler, you will still get the response to your form with the following method.
jQuery('#contactForm').on('submit', function (e) {
if (document.getElementById("contactForm").checkValidity()) {
e.preventDefault();
jQuery.ajax({
url: '/some/url',
method: 'POST',
data: jQuery('#contactForm').serialize(),
success: function (response) {
//do stuff with response
}
})
}
return true;
});
Not exactly sure what you mean. But I assume that you want to check in realtime if the input is valid. If so you should use .keyup instead of .click event, because this would lead to an action if the user presses submit. Look at http://api.jquery.com/keyup/
With this you could check the input with every new character insert and display e.g. "not valid" until your validation ist true.
I hope this answers your question!
U can also use jquery validate method to validate form like
$("#form id").validate();
which return boolean value based on form validation & also u can see the error in log using errorList method.
for use above functionality u must include jquery.validate.js file in your script

reCAPTCHA Invisible - reSubmit Form Issue

While using reCaptcha, I faced a problem. In code, using AJAX to submit form. Before submitting I need to check if the fields are filled or not. If fields are not filled, submit should not happen.
In this case, if textfields are not filled, it will give an alert.
The problem is after the rejection of invalid post, the submit button stops working for like 2 or 3 minutes and there is no error given by reCaptcha. After the period of time, reCaptcha starts working again and submit button works.
<form id="contact-form" method="post" action="javascript:void(0)">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="E-Mail" id="email">
<textarea placeholder="Message" id="message">/textarea>
<button class="g-recaptcha pull-right" data-sitekey="#your-site-key" data-callback="sendData" type="submit"> SEND <i class="flaticon-origami34"></i> </button>
</form>
Javascripts :
function sendData(){
console.log('send data - '); // --> works
//send datas:
$("#contact-form").submit();
};
$('#contact-form').on("submit", function() {
console.log('clicked submit'); // --> works
name = $('#name').val().replace(/<|>/g, ""), // prevent xss
email = $('#email').val().replace(/<|>/g, ""),
msg = $('#message').val().replace(/<|>/g, "");
if (name == '' || email == '' || msg == '') {
alert("Please fill all areas !");
} else {
console.log('captcha response: ' + grecaptcha.getResponse()); // --> captcha response:
// ajax to the php file to send the mail
$.ajax({
type: "POST",
url: "SaveContact.php",
data: "email=" + email + "&name=" + name + "&msg=" + msg + "&g-recaptcha-response=" + grecaptcha.getResponse()
}).done(function(status) {
if (status == "ok") {
// clear the form fields
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
});
}});
According to the documentation, you can also call grecaptcha.reset(opt_widget_id);, where opt_widget_id is optional and will default to the first recaptcha widget created.
Then you need to reset cooldown of invisible recaptcha, you could use a hack like this
var recaptchaIframe = document.querySelector('.grecaptcha-badge iframe');
recaptchaIframe.src = recaptchaIframe.src;
I don't have a better solution.
Figured this out and wanted to post it in case anyone else has the same issue. Google's example code set's the button id as "submit" and calling the "submit" function from within onSubmit was failing because of it. Changing the id to anything else fixed it.
if you render recaptcha explicitly in a script like this:
var form = grecaptcha.render('idSelector', {
'sitekey' : 'your_sitekey',
'callback': callableFunction
}, true)
then, "form" variable contains widget_id, so you can reset that recaptcha like this
grecaptcha.reset(form);

Trying to get Captcha working alongside my validation

I have managed to validate my textboxes using JS but know I need to allow the captcha to work alongside the validation.
<script>
function validateForm() {
var x = document.forms["reg"]["User"].value;
var letters = "#";
if (x.match(letters))
{
alert("Can't Have Email Address As USERNAME!");
return false;
}
return true;
}
First Form
<form name="reg" action="DBLogin.php" onsubmit="return validateForm()" method="post">
Captcha:
<form action="validate.php" method="post">
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Register">
</form>
Is there a way of having the captcha work alongside my JS validation?
Thank you
use ajax to validate the captcha. and when he submits the form send an ajax request to verify captcha.
give a submit button only to the captcha form.
<form id ="captcha-form" >
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Register">
</form>
main form :
<form id="main-form" name="reg" action="DBLogin.php" method="post">
<!-- this shoulnt have an submit button -->
now use a js code to first verify the captcha and validate form
$("#captcha-form").submit(function(event){
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "validate.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
if(response == "true")
{
validateform();
}
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// handle error
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
now the validate function
function validateForm() {
var x = document.forms["reg"]["User"].value;
var letters = "#";
if (x.match(letters))
{
alert("Can't Have Email Address As USERNAME!");
}
$("#main-form").submit();
}
as RiggsFolly has pointed out this is not recommended. as this would defeat the purpose of captcha.

trying to post with jquery ajax without leaving the page

Im following this question trying to post to a php page and have it perform an action on the data the problem is it seems to just refresh the page and not sure what its doing. In the network tab in element inspector my php page never appears.
Here is my code:
js:
<script>
$(function () {
$("#foo").submit(function(event){
// variable to hold request
var request;
// bind to the submit event of our form
// abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "/DormDumpster/session/login-exec.php",
type: "post",
data: json
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
alert("hello");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
alert("bye");
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
});
html:
<form id = "foo" method="post" >
<fieldset id="inputs">
<input id="email" type="email" name="login" placeholder="Your email address" required> <br>
<input id="password" type="password" name="password" placeholder="Password" required>
</fieldset>
<fieldset id="actions"">
<input type="submit" id="submit" name "Submit" value="Log in"">
<label><input type="checkbox" checked="checked"> Keep me signed in</label>
</fieldset>
</form>
php
$email = clean($_POST['login']);
$password = clean($_POST['password']);
Any Ideas to what I am doing wrong or how to figure out what im doing wrong.
You are probably trying to attach the event listener prior to the form being available in the DOM - thus your form won't be found and no event listener will be attached. Try wrapping your code in a DOM-ready callback, to make sure that your form is in the DOM before trying to select it.
$(function () {
$("#foo").submit(function(event){
// All your code...
});
});
More on why and when to use DOM-ready callbacks here.
i think you have to wrap your submit function inside doc ready:
$(function(){
// here your form submit
});
It is always good to note what arguments you are passing as parameters and to check if it is valid within that function or property.
$(function(ready) {
$.ajax({
type: "POST",
url: "/DormDumpster/session/login-exec.php",
data: { name: "John", location: "Boston" },
dataType: "JSON"
})
}
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests.
- from http://api.jquery.com/jQuery.ajax/

Categories