I am using the following code to allow users to submit content to an online board:
$('form').submit(function(){
var form = $(this);
var name = form.find("input[name='name']").val();
var code = form.find("input[name='code']").val();
var content = form.find("input[name='content']").val();
if (name == '' || content == '')
return false;
$.post(form.attr('action'), {'name': name, 'code' : code, 'content': content}, function(data, status){
$('<li class="pending" />').text(content).prepend($('<small />').text(name)).appendTo('ul#messages');
$('ul#messages').scrollTop( $('ul#messages').get(0).scrollHeight );
form.find("input[name='content']").val('').focus();
});
return false;
});
Unfortunately, if a user rapidly presses enter or rapidly clicks the send button, the code will execute multiple times and their message will be sent multiple times.
How can I modify my code to prevent this multiple execution?
A simple client-side fix would be to create a local variable that tracks whether or not anything has been submitted and have the function only execute if false.
var submitted = false;
$('form').submit(function(){
var form = $(this);
var name = form.find("input[name='name']").val();
var code = form.find("input[name='code']").val();
var content = form.find("input[name='content']").val();
if (name == '' || content == '')
return false;
if (submitted)
return false;
submitted = true;
$.post(form.attr('action'), {'name': name, 'code' : code, 'content': content}, function(data, status){
$('<li class="pending" />').text(content).prepend($('<small />').text(name)).appendTo('ul#messages');
$('ul#messages').scrollTop( $('ul#messages').get(0).scrollHeight );
form.find("input[name='content']").val('').focus();
});
return false;
});
A better solution would be to send a unique token for the transaction to the client and have the client send it along with the request.
You could have server-side coded to verify that the token has only been used once.
found this solution here
$("form").submit(function () {
if ($(this).valid()) {
$(this).submit(function () {
return false;
});
return true;
}
else {
return false;
}
});
Related
I am creating a form that asks for email and password and validates it. If it has any error, it pops on the same line. Below is my javascript code for it. When I fill the form and hit submit, the values get reset. Moreover, I do not see anything in the console. I tried using a random code console.log('Hanee') to test my code but nothing gets generated in the console tab. Could anyone tell me what's the issue here?
Also, here's the link to my login form: http://www2.cs.uregina.ca/~hsb833/215a/login.html
document.getElementById("login-form").addEventListener("submit",validateLogin,false);
function validateLogin(event){
var elements = event.currentTarget;
var emailValue = elements[0].value;
var passValue = elements[1].value;
checkEmail(emailValue);
checkPass(passValue);
}
function checkEmail(emailValue){
var regex_email = /^[/w]+#[a-zA-Z]+?\.[a-zA-Z]{2,3}$/;
var index = emailValue.search(regex_email);
var errorEmail = document.getElementById("errorEmail");
var valid = true;
console.log('Hanee');
if(index != 0){
errorEmail.style.display = 'inline';
}
}
function checkPass(passValue){
var password = document.getElementById("password");
var regex_pass = /[\w]+\S/;
var index = passValue.search(regex_pass);
if(passValue.length < 6){
console.log('password is invalid. Minimum length is 6');
errorPassLen.style.display = 'inline';
}
if(index != 0){
console.log('password is invalid. Please make sure there is no spaces in between');
errorPassFormat.style.display = 'inline';
}
}
form is refreshed after being submitted by default. To prevent that, use event.preventDefault(); in your validateLogin
Here is an example of a form with a username and password, maybe it will suit you and you can customize it for your needs
async function tebeFxhr() {
let logfil = 1;
let sotebe= false;
let tes =(logt) => {
return /^[a-zA-Z0-9]+$/ui.test(logt);
}
tes(gtebe)==true ? logfil++ : alert('Login cannot contain characters or spaces')
let textrf =(rutext) => {
return /[а-я]/i.test(rutext);
}
textrf(stebe)==true ? alert('The password cannot contain Cyrillic characters') : logfil++;
stebe.length < 8 ? alert('Password is very short') : logfil++;
stebe===ftebe ? logfil++ : alert('Enter the password 2 times so that they match')
if (logfil === 5){
const data = {data_0:gtebe, data_1:stebe, data_2:ftebe};
const response = await fetch("/form", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then((response) => {
return response.text();
})
.then((sotebe) => {
console.log(sotebe)
if(sotebe==='error-1'){
console.log('error-1')
}
else{
sotebe =='' ? location.replace("../") : alert(sotebe)
}
});
}
}
When submit event is triggered, all values are sent to server and get reset. If you want to prevent this, use event.preventDefault(); inside the event handling function validateLogin(event). Then, the values are not going to be reset!
Still If you want your values to be empty after submission, try below.
elements.forEach(e => e.value = '');
hello i have a login validation form which uses a mix of jquery and ajax to do validations... if the values are ok the form should submit, if the values are not ok then the form should not submit... however in my case the form is submitting even when the values are incorrect ( i am using the mousedown function ) please see below my code..
<form method="post" name="loginform" action="models/login.php">
<input type="email" class="homepage" name="user_email2" id="user_email2" placeholder="Email" maxlength="50" />
<div class="errormsg" id="errormsg6"></div>
<input type="password" class="homepage" name="user_password2" id="user_password2" placeholder="Password" maxlength="20" />
<div class="errormsg" id="errormsg7"></div>
<input type="submit" name="login" id="login" value="Submit">
<div class="errormsglast" id="errormsg8"></div>
</form>
jquery and ajax
$(document).ready(function()
{
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_emailajax2 = "";
var user_password2 = "";
var user_passwordajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Email */
var validate_email_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
if (item5.length < 6 || item5.length > 50)
{
$("#errormsg6").html("Email : 6 - 50 Characters");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
if (!emailformat.test(item5))
{
$("#errormsg6").html("Wrong Email Format");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
$.ajax(
{
type: 'POST',
url: 'classes/validatelogin.php?f=1',
data: "user_email2=" + item5,
success: function(msg)
{
if (msg == "ok")
{
user_emailajax2 = "";
$("#errormsg6").html("Email Does Not Exist");
}
else if (msg == "exists")
{
user_emailajax2 = item5;
$("#errormsg6").html("");
}
}
});
}
}
}
/* ----------------- Define Validate Password */
var validate_password_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20)
{
$("#errormsg7").html("Password : 8-20 Characters");
user_password2 = "";
}
else
{
$("#errormsg7").html("");
user_password2 = item6;
if (user_email2 != "" && user_emailajax2 != "")
{
$.ajax(
{
method: "POST",
url: "classes/validatelogin.php?f=2",
data: "user_email2=" + item5 + "&user_password2=" + item6,
success: function(msg)
{
if (msg == "WrongPw")
{
user_passwordajax2 = "";
$("#errormsg7").html("Wrong Password - See Forgot Password");
}
else if (msg == "CorrectPw")
{
user_passwordajax2 = item6;
$("#errormsg7").html("");
/* window.location.href="manage-properties"; */
}
}
});
}
}
}
/* ----------------- Run Functions */
$("#user_email2").on('focusout', validate_email_login);
$("#user_password2").on('focusout', validate_password_login);
/* ----------------- Stop on Submit */
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
return true;
}
});
});
Solution Tried - problem is that when user puts the wrong event that is fine, but if user then puts the correct values, the submit returns false on first time, then second time it returns true... it should return true in first go
<input type="button" name="login" id="login" value="Submit">
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
$('[name=loginform]').submit();
}
});
});
Instead of having a type="submit" button just have a normal button e.g<input type="button" name="login" id="login" value="Submit">. Then when you finished checking the values and happy that it should send then just call:
$('[name=loginform]').submit();
Because what is happening currently is that the form submits when you click on the button, because you are not stopping that event from happening.
If you want to prevent the form from submitting I would suggest either not using that button and initiating the submit yourself like I mentioned above, or alternatively you can use the onsubmit="someFunction()" on the form element way and just return false if it should not submit and return true if it should.
I would say your code suffers from a few issues and some bad practices.
I see you are trying to learn JS so forgive me for not directly solving your issue but to give you some pointers and point you to some best practices.
Logic -
It seems like you are doing a login form. I would say most of this checks should not happen in the client but on the server.
When user signups it might be wise to check user name length on the client as well and prompt the user that he can't use the user name he wants to register with, but during login all the client care is can I login or not.
Security -
You seem to have two serious security issues with your code
You allow to test if an e-mail/user exist or not using 'classes/validatelogin.php?f=1'. in general you should always test the user and password together if they exist and match the user should be able to login, if not the login should fail. you shouldn't notify the user why it fails (if the user name does not exist or if it exist but the password is wrong).
You don't seem to hash passwords in the database. I assume it by limiting the password max length. let the user choose as long password as he wants and hash it using a secure hashing algorithm (I'd suggest bcrypt but google around and find a suitable one). I know you are only learning but this is highly important I think hashing is the first thing you need to learn when handling user logins
Working with the DOM.
You should cache your DOM elements
so instead of calling $('#id') all the time in the main function scope set
var emailInput = $("#user_email2");
function submitForm() {
var email = emailInput.val().toLowerCase();
...
}
You should also probably set the text value of the element and not the html doesn't matter much now but since you are setting text value its good practice and will help you avoid unexpected injections and errors.
Since your using ajax you should not let the form to submit itself even when validation is successful.
Common logic should be packed into functions and reused.
There are many places where your original code can be split into shorter and reusable functions
handle async code better
jQuery supports the Promise API when using ajax requests, I would rather use it. Your original code had a few async calls if you needed to sync between them it would have been painful using plain callbacks (and it is probably what caused you issues in the first place)
Here is a simplified solution using my suggestions -
$(document).ready(function() {
"use strict";
var emailInput = $("#user_email2"),
emailError = $("#errormsg6"),
passwordInput = $("#user_password2"),
passwordError = $("#errormsg7");
function required (value) {
if (value) {
return true;
} else {
return false;
}
//this is just to make the code clear you could use
//`return value ? true : false` or `return !!value`
}
$('form:eq(0)').on('submit', function (e) {
var valid = true,
email = emailInput.val(),
password = passwordInput.val();
e.preventDefault();
if ( !required(email) ) {
emailError.text('Email is required');
valid = false;
}
if ( !required(password) ) {
passwordError.text('Password is required');
valid = false;
}
if ( valid ) {
$.ajax({
method: "POST",
url: "login.php",
data: {
email: email,
password: password
}
}).done(function (data, textStatus, jqXHR) {
//redirect user to main page
}).fail(function (jqXHR, textStatus, errorThrown) {
//show the user the error
})
}
});
});
I am working on a registration form with jquery ajax. My jQuery Code is as follow :
function validateData()
{
var email = jQuery("#email").val();
var username = jQuery("#username").val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var regex = new RegExp(/^\+?[0-9(),.-]+$/);
if(!emailReg.test(email))
{
alert('Please enter valid email');
return false;
}
var agreement = jQuery("#agereement").is(":checked");
if(agreement == false)
{
alert("Please agree with the agreement !!! ");
return false;
}
var pass = jQuery("#password").val();
var repass = jQuery("#repeatpass").val();
if(pass != repass)
{
alert("Password & Repeat Password Should be same");
return false;
}
var FirstData = "email=" + email+"&username="+username;
var url = "ajaxcheck.php";
jQuery.ajax({
dataType : 'html',
type: 'GET',
url : url,
data : FirstData,
complete : function() { },
success: function(data)
{
if(data == '')
{
alert("No Problem");
var flag = "true";
}
else{
alert("Username Or Email ID Already Exists");
var flag = "false";
}
}
});
alert(flag);
return flag;
}
</script>
When I submit the form and enters the value of username which is already exists in DB then it alerts the Username Or Email ID Already Exists but submit the form instead of staying on the page. What Should I do if it error comes then it should stay on the page instead of submitting the form
When you write:
var flag = "true";
…
var flag = "false";
…
return flag;
The problem is that "true" and "false" are strings containing the word “true” or “false”. To get the actual boolean values true or false, get rid of the quotes:
var flag = true;
…
var flag = false;
…
return flag;
Event handlers only understand boolean return values, not strings.
Use onsubmit in form tag
<form onsubmit="return validateData();">
....
<input type="submit">
</form>
I'm trying to help you from another angle.
Here is an example on how to do form validation (with bootstrap/php/jquery): http://formvalidation.io/examples/contact-form/
Ajax ".done" happens when you get a successful response from the server and ".fail" happens when sending a request or receiving the response has failed. Assuming you want to check if email exists then you can use something in the lines of:
if(response.IsEmailValid === 'false')
{
$('#alertContainer')
.removeClass('alert-success')
.addClass('alert-warning')
.html('Sorry, email has been taken')
.show()
}
You're setting flag to strings, not boolean values. Try using true and false instead of "true" and "false", both of which are truthy.
I have this partially working code. What it suppose to do is to check for existing email address in database. If no email exist then return true;
$(document).ready(function() {
var email_check = 0;
var checking_html = '<img src="http://i.imgur.com/Y8wXAZp.gif" /> Checking...';
var characters_error = 'Minimum amount of chars is 6';
//when button is clicked
$('.register').click(function(){
//run the character number check
if($('#email').val().length < 1){
$('#email_result').html(characters_error);
return false;
}
else{
//else show the cheking_text and run the function to check
$('#email_result').html(checking_html);
alert(check_email_availability());
}
});
});
//function to check email availability
function check_email_availability(){
//get the email
var email = $('#email').val();
//use ajax to run the check
$.post("check_email.php", { email: email },
function(result){
email_check = 0;
//if the result is 1
if(result == 1){
//show that the email is available
email_check = 1;
}else{
email_check = 0;
}
});
if (email_check == 1){
return true;
}else{
return false;
}
}
Now, the problem is if current state is false, when I enter an email that is not available in the db and click button, I still get false alert, and when the next time I click button I get true alert. For some reason the function execute bottom code first (checking email_check value) and after that it execute the function. Why is that? What is wrong with my code? How can I make it execute function and then check the email_check value whether 1 or not?
I would change this to put an ajax success callback on your check function something along the lines of.
success: function (data, status, xhr ) {
myFunctionShowEmailSuccess();
},
error: function (xhr, status, error) {
myFunctionShowEmailFailure();
}
Try doing this.
//function to check email availability
function check_email_availability(){
//get the email
var email = $('#email').val();
//use ajax to run the check
$.post("check_email.php", { email: email },
function(result){
email_check = 0;
//if the result is 1
if(result == 1){
//show that the email is available
return true;
}else{
return false;
}
});
}
I'm making a simple form where a user submits a video, alongside their email address. I'd like to make it so that the person can not submit the form until they have filled in the email and saved the video.
The video part is working, but when I test with an empty email, it still seems to submit. The code is below, and the live version is at http://www.atlas-china.com/record-your-multi-lingual-abilties/
Help much appreciated!
// Global variable to hold player's reference.
var _Nimbb;
// Global variable to hold the guid of the recorded video.
var _Guid = "";
// Event: Nimbb Player has been initialized and is ready.
function Nimbb_initCompleted(idPlayer) {
// Get a reference to the player since it was successfully created.
_Nimbb = document[idPlayer];
}
// Event: the video was saved.
function Nimbb_videoSaved(idPlayer) {
_Guid = _Nimbb.getGuid();
}
jQuery(document).ready(function ($) {
// Get the data from the form. Check that everything is completed.
$('#video_submit').click(function (e) {
var email = document.getElementById("email").value;
var video_title = document.getElementById("video_title").value;
var form = document.myForm;
// Make sure the email is specified.
if (email.value == "") {
alert("Please enter your email to proceed.");
return;
}
// Verify that the video is not currently recording.
if (_Nimbb.getState() == "recording") {
alert("The video is being recorded. Please wait.");
return;
}
// Check that video has been recorded.
if (_Guid == "") {
alert("You did not save the video. Click save.");
return;
}
// Set the guid as hidden parameter.
form.guid.value = _Guid;
var dataString = 'email=' + email + '&guid=' + _Guid + '&video_title=' + video_title;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri();?>/send.php",
data: dataString,
success: function () {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
}
});
document.forms["myForm"].submit();
});
});
After viewing your live site...
email = "" // Empty string
Whereas
email.value = undefined
Try changing your code to
if (email === "") {
alert("Please enter your email to proceed.");
return;
}
I assume you are doing .value twice by mistake as you have the following line earlier in your code
var email = document.getElementById("email").value;
When you return from that handler function, the browser will proceed to carry out the normal behavior of the "submit" event, which is to submit the form.
You can change your "abort" return statements to
return false;