Cancelling a form submission, then submitting it again - javascript

So I have a login form. What I want I am currently doing is submitting the form using action="" etc.. with an onSubmit even with my form validation inside the javascript function validate(). Currently though it will submit the form and validate at the same time. What I want to happen is for it to not submit the form, or to cancel it as soon as we get into the validate function. And then if the forms are valid, submit the form.
This is my logic behind what I want to do
function validate() {
stopFormSubmit();
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != "") {
submitForm();
} else {
displayErrors();
}
}
My form looks like this
<form onSubmit="validate()" name="basicForm" id="basicForm" class="basicForm" action="login.php" method="post" autocomplete="off">
Is there anyway to do this?

The form does validate and then submit. Validation just takes very little time.
What you really want to do is to stop the form if it fails validation.
Using intrinsic event attributes, return false to stop the form being submitted. Since that is determined by the success of the validation, you need to return true or false from validate and then return that from your event handler.
onSubmit="return validate()"
and
function validate() {
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != "") {
return true;
} else {
displayErrors();
return false;
}
}
Modern code would use unobtrusive JavaScript and bind the event handlers programatically. Then it would use the Event object to control that happened to the default behaviour. Since you are already using jQuery, we can use that to perform the event binding.
Remove the onsubmit attribute entirely.
jQuery('form').on('submit', validate); // Run this after the form exists in the DOM
and
function validate(evt) {
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != "") {
// Do nothing
} else {
displayErrors();
evt.preventDefault();
}
}

I suggest to use jQuery Validation plugin, if possible.
Another idea - to do like here:
1. onSubmit="return validate()"
2. Update function:
function validate() {
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != "") {
submitForm();
// or you can simply return true to allow form data submitting
} else {
displayErrors();
return false;
}
}

Related

Obtaining output of php file with Javascript

I have a php file stored remotely. It uses post to take 2 variables, "username" and "password", which will then echo either Valid or Invalid depending on it's existence in my database. I currently use this with my android application to log users in.
I would like to use this same script for logging into my website that I am building. I need to be able to pass 2 variables that I have obtained from an HTML form to a javascript function which will take the variables, run them though the php query, read the echoed output and decide to return true or false to the form. Below is the code I currently have for the script
Javascript code:
<script type="text/javascript">
function Login(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert ("Please fill in username and password fields");
return false;
}
$.post("my_query_url.php",{username:username, password:password}, function(data) {
if (data.toLowerCase == "valid")
return true;
else
return false;
});
}
</script>
HTML form:
<form action="Main.html" method="post" onsubmit=" return Login();">
Username: <br>
<input type="text" name="username" id="username"><br>
Password: <br>
<input type="password" name="password" id="password"><br><br>
<input type="submit" value="Login">
</form>
Currently, it always sends the user to my Main.html page with any non-empty username/password input.
I'm not very well versed in these two languages, but I need to learn quickly as they are important for my Senior Project class semester, and especially these next two weeks. Is this possible to do with Javascript and HTML only? Some pointers will be much appreciated! Thank you!
You actually are almost all the way there. You just need to return false from your Login function to prevent the default action of the form from triggering (which is to redirect to main.html). Then, instead of relying on the form to redirect the user, you will need to do so yourself via javascript.
<script type="text/javascript">
function Login(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert ("Please fill in username and password fields");
return false;
}
$.post("my_query_url.php",{username:username, password:password}, function(data) {
if (data.toLowerCase() === "valid")
window.location.href = "./Main.html"; //redirect the user
else
return false;
});
return false
}
</script>

prevent button form from submission Javascript

This form keeps on submitting even if it executes the return value, what is the problem with my code?
function formhash (form, password)
{
var pass1 = document.getElementById("password").value;
var pass2 = document.getElementById("cpassword").value;
var ok = true;
if (password != cpassword) {
//alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("cpassword").style.borderColor = "#E34234";
ok = false;
return;
}
else
{
$.post('insert_home.php'
{PRIMAID:PRIMAID,EDITCAP:EDITCAP,EDITIMG:EDITIMG,EB_TITLE:EB_TITLE}).done(function(data){
alert ("Book Successfully Updated");
location.reload();
});
var p = document.createElement("input");
form.appendChild(p);
p.name="p";
p.type="hidden";
p.value=hex_sha512(password.value);
password.value="";
form.submit();
}
}
You are calling form.submit();, remove it and it won't submit.
You are using the wrong variable names "password" and cpassword". You created pass1 and pass2 so you need to use those.
Change to this:
//You were using the WRONG variable names
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("cpassword").style.borderColor = "#E34234";
ok = false;
return false;
}
I don't see where formhash() is used.
The code calls the submit, not the function.
If it submits the form, it' because it's falling in the else condition.
Add lots of "console.log("debug_X")" where "X" is a number different each time.
You have to add inside a console.log the value of pass1 and pass2.
Maybe you are passign a value instead of an object or maybe the reversed situation can happen also.
My instinct tells me to check both password object, and their values.
Also it tells me that you didn't check the content of pass1 and pass2 before posting a comment to Don Rhummy.
Check carefully and please search more before posting your next answer.
You can have the value by doing "console.log(pass1);" and by opening firebug and by checking the javascript console.
Remove Action attribute from Form.

AJAX stored requests and form submitting

I am working on a jQuery validation "plugin" (not yet a plugin) that use my Zend_Form validators to verify the fields before submitting, client-side, so I only have to specify my constraints one time instead of two (Zend Validators + jQuery Validate Plugin, for example).
I store the validation AJAX requests for each field, then wait for them to finish, and then read the results and show or not an error message.
The problem : when I enter validated strings and hit submit, it shows no errors (good so far), but I have to re-click the submit button the form to really submit it.
Making a return true or false inside the .whenAll function is ignored and does not work, that's why I used a flag to tell the function if yes or no it can really submit the form.
$(function() {
var form = $('form'); // target form
var requests = [], validations = []; // used to store async requests and their results
var nbInputs = $('input[type="text"], input[type="password"]').length; // number of inputs we want to check in the form
var cancelSubmit = true; // skip validation flag
form.submit(function( ) {
// if we call the submit inside the function, skip validation and do submit the form
if(cancelSubmit === false) {
console.log('[-] cancelSubmit is false. Validation skipped.');
this.submit();
return true;
}
console.log('[-] Entering validation');
// resetting requests and validations
requests.length = 0;
validations.length = 0;
// for each input (text/password), storing the validation request
$('input[type="text"], input[type="password"]').each(function(i) {
var validatorField = $(this).attr('data-validator');
var valueField = $(this).val();
postData = {
validator: validatorField,
value: valueField
};
// storing requests into an array
requests.push($.post('/validate', postData));
});
(function($) {
$.whenAll = function() {
return $.when.apply($, arguments);
};
})(jQuery);
// when all the requests are done and returned a response
$.whenAll(requests).then(function() {
// show the validation status for each input
$.each(requests, function(i, element) {
element.done(function(data) {
// response is formatted like this
// { valid: 1 } or { valid: 0, message:"This is the error message" }
json = $.parseJSON(data);
formGroup = $('input:eq('+i+')').parent();
// if it isn't valid, show error and store result
if(json.valid == 0) {
if($('span.help-block', formGroup).length == 0) {
$(formGroup).addClass('has-error').append('<span class="help-block">'+json.message+'</span>');
$('label', formGroup).addClass('control-label');
}
validations.push(0);
}
// else, remove error (if there was) and store the result
else if(json.valid == 1) {
if($(formGroup).hasClass('has-error'))
{
$(formGroup).removeClass('has-error');
$('.help-block', formGroup).remove();
}
validations.push(1);
}
// if we got all the validations required
if(validations.length == nbInputs)
{
console.log('[-] All validations have been done.');
// and if no error ("0") in the results, we resubmit the form with skip-flag
if($.inArray(0, validations) == -1){
console.log('[-] No errors. Submitting form.');
cancelSubmit = false;
form.off('submit');
form.submit();
}
else
console.log('[-] There is still errors.');
}
});
});
});
// there are errors, so we won't submit the form
if(cancelSubmit === true)
return false;
});
});
Do you see a logic flaw in my code ? Maybe re-submitting the form with a flag isn't the right way to do it ?
You're returning from a sub scope rather than from the form submit handler. Instead, always prevent the submit, and then force it to submit with form[0].submit() when you want it to submit.
form.submit(function(e) {
e.preventDefault();
...
// now i want to submit...
form[0].submit();
form[0].submit() will bypass your jquery bound submit handler.

Validate form using jQuery

When a form submit button is clicked, a function to validate all the field is to be called. Nothing is to happen, however, if the validation fails.
I am using mailto: as my action, does this make a difference?
I would like to get clarification on two things:
Is this the correct way to call a function when clicking the submit button?
$(document).ready(function(){
$('#contactForm').submit(function(){
checkMail();
});
});
Can I still validate the fields even though I'm using mailto:?
Here is the rest of the code:
function checkEmail(){
var email = document.contact.email.value;
if(email == "") {
document.getElemtById("email_error").innerHTML = "No Email Address";
return false;
}
else {
document.getElementById("email_error").innerHTML = ""
return true;
}
}
HTML:
<form name="contact" action="mailto:exampleemail#hotmail.com" method="post">
<li>
<label for="email">Email</label>
<input id="email" type="text" name="email" placeholder="Enter Email Address">
</li>
<span id="email_error"></span>
Further, I don't get an error message on clicking submit.
No, you need the event handler to return false in case the validation failed. This will prevent the action from being executed, i.e. the mail program from being launched.
we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler.
Source
Modify it like this:
$(document).ready(function(){
$('#contactForm').submit(function(){
return validate();
});
});
Of course, this implies that the validate() function needs to actually return false in case the validation fails, and true otherwise.
Further you are missing id="contactForm" on your <form> tag.
Also, you need to grab the email value correctly:
var email = $("#email").val();
There's another mistake: You misspelled getElementById(). Here's a corrected version:
function checkEmail() {
var email = $("#email").val();
if (email == "") {
document.getElementById("email_error").innerHTML = "No Email Address";
return false;
}
else {
document.getElementById("email_error").innerHTML = ""
return true;
}
}
Or alternatively, using all jQuery:
function checkEmail() {
var email = $("#email").val();
var $error = $("#email_error");
if (email == "") {
$error.html("No Email Address");
return false;
}
else {
$error.html("");
return true;
}
}
Here's what you need:
$(document).ready(function(){
$('#contactForm').submit(function(){
if (!validate()) {
return false; // Prevent the submit
}
});
});
For validating the fields of your form, before sending it, you can use the jQuery's validation plugin:
$(document).ready(function(){
$("#contactForm").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
});
Check the online doc for more information and examples: http://docs.jquery.com/Plugins/Validation#Validate_forms_like_you.27ve_never_been_validating_before.21

Form submission will not stop for validation

What I am trying to accomplish is a (very simple) email validation using jQuery, but no matter what I do, the form will just keep submitting.
<form id="rfq" name="rfq" action="rfq_form" method="post" enctype="multipart/form-data">
...
<input type="image" id="submit" name="submit" src="submit.png" border="0" />
JS email validation:
//$("#rfq").submit(function() { doesnt seem to work either
$('#submit').click(function() {
var email = $('#email').val();
if(email.indexOf("#") == -1){
$("#email").addClass('invalid');
return false; // cancel form submission if email invalid
}
return false; // return true if no errors once i get it working
});
Working Example
First, make sure all event handlers are attached once the DOM is "ready"
I'm using .submit() on the actual form.
$(document).ready(function() {
// now that document is "ready"
$('#formId').submit(function() {
var email = $('#emailInput').val();
alert(email);
if(email.indexOf("#") == -1){
alert("invalid!");
return false; // cancel form submission if email invalid
}
alert("valid!");
return true; // return true if no errors once i get it working
});
});
Try wrapping your code in a ready block.
$(document).ready(function(){
// your code here
});
You should also be using the submit event on the <form> element, I think.
This is going to work. If you don't understand why, feel free to ask :)
var validated = false;
$(document).ready(function(){
$("#rfq").submit(function(event) {
if (validated === true) {
return true;
}
event.preventDefault(); // prevent submission
var email = $('#email').val();
if(email.indexOf("#") == -1){
$("#email").addClass('invalid');
return;
}
validated = true;
return $(this).trigger('submit');
});
});
You could try using this function to validate your address.
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
And then modify your code to submit the form.
$('#submit').click(function() {
var email = $('#email').val();
if(!validateEmail(email)){
$("#email").addClass('invalid');
}
else {
$("form").submit();
}
});

Categories

Resources