Trying to get Captcha working alongside my validation - javascript

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.

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

HTML5 required attribute not working with AJAX submission

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>

Call php in HTML form on action but don't redirect

I have an HTML form as follows:
<form id="ContactForm" name="ContactForm" method="post" action="emailinfo.php">
and then a submit button that calls verify():
Send
verify is defined as such:
function verify() {
if(document.getElementById("name").value=="" || document.getElementById("email").value=="") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
document.getElementById('ContactForm').submit();
}
}
Currently, when I click the submit button, the browser redirects to emailinfo.php, which is just a blank white screen because that php file just sends off an email and does nothing else. How can I run that php file without redirecting to it?
What you want to do is use AJAX to send a request to the emailinfo.php file when the button is clicked. Making the form action blank will cause the form to post to the same page you're on.
If you're using jQuery, it's pretty easy to submit the form via ajax:
$(document).ready( function() {
$('.button1').click(function(){
var f = $('#ContactForm');
$.ajax({
type: "POST",
url: "emailinfo.php",
data: f.serialize()
});
});
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function verify() {
if(document.getElementById("name").value=="" || document.getElementById("email").value=="") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
//document.getElementById('ContactForm').submit();
var name=$('#name').val();
var email=$('#email').val();
var formData = "name="+name+"&email="+email;
$.ajax({
url : "emailinfo.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
//data - response from server
alert(data);
},
});
}
}
</script>
<form id="ContactForm" name="ContactForm" method="post" action="">
<input type="text" name="name" id="name"/>
<input type="text" name="email" id="email"/>
Send
</form>
ContactFormFirst change that a tag to a button, then assign that verify() to its onclick. then in verify(). use ajax to post the values from your form to emailinfo.php.
u can use
$.post(
"emailinfo.php",
$( "#ContactForm" ).serialize(),
function( data ) {
/* do things with responce */
} );
What I usually do in this scenario is ajax, but if you do not want to use ajax, you can simply add 'return false' for it not to be redirected when using form submit:
function verify()
{
if(document.getElementById("name").value=="" ||document.getElementById("email").value=="")
{
alert("Please enter a name and an email.");
}
else
{
alert("Looks good, sending email");
document.getElementById('ContactForm').submit();
return false;
}
}

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