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;
}
});
}
Related
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;
}
});
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.
when i click a button i want to validate two functions one by one and my functions are
validateEmail(email);
validatemobile(mobile);
what i am trying so far and my code is
when i click getotp button
$('.getotp').click(function(e) {
e.preventDefault();
var response;
var email=$('#email').val();
validateEmail(email);
if(response=true){
var mobile=$('#mob').val();
validatemobile(mobile);}});
my emailvalidation function is
function validateEmail(email){
var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
var valid = emailReg.test(email);
if(!valid)
{
$('.errornotice').text('Email Address Is Not Valid');
response=false;
}
else
{
response=true;
}
}//email validate function
and my mobile validation function is
function validatemobile(mobile){
//CHECK MOBILE NUMBER
if(mobile=='')
{
$('.errornotice').removeClass('nodisplay');
$('.errornotice').text('Mobile Number can not be empty');
e.preventDefault();
}
else if(mobile.toString().length>10 || mobile.toString().length<10 )
{
$('.errornotice').removeClass('nodisplay');
$('.errornotice').text('Mobile Number Must be 10 Digit');
e.preventDefault();
}
//send OTP
else
{
e.preventDefault();
$.ajax({
type:'POST',
url:"otp.php",
data:{mob:mobile},
success: function(data){
e.preventDefault();
$('.errornotice').text('check your mobile and enter OTP');
}//success
})//ajax
}//else
}//mobile validate function
I have a problem with checking for e-mail availability with the custom function of LiveValidation: it keeps sending back that the e-mail is already in use even if it isn't.
Can someone please help me out of this ?
-- EDIT--
I figured out that the function check_availability can't return the true or false from the Ajax call. So I'm almost there I just need to make the function return the right bool value.
This is my code until now:
JS File:
//function to check username availability
var check_availability = function(){
//get the username
var email = $('#email').val();
//use ajax to run the check
$.post("checkEmail.php", { email: email },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
return true;
}else{
//show that the username is NOT available
return false;
}
});
// Validation
var mail = new LiveValidation('email', { validMessage: "Ok!" });
mail.add( Validate.Custom,{failureMessage:"E-mail is al in gebruik!",
against: function(){ return check_availability() }
});
checkEmail.php file:
<?php
require_once 'db_config.php';
//Controleren of e-mail adress al in gebruik is
$sql_select_email = "SELECT email from tblUsers WHERE email = '".mysql_real_escape_string($_POST['email'])."'";
if (($result_select_email = mysql_query($sql_select_email)) === false)
{
# als de query fout is -> foutafhandeling
echo showSQLError($sql_select_email,mysql_error(),'Fout bij het opvragen van de gegevens.');
}
else
{
//Query gelukt
$count_email = mysql_num_rows($result_select_email);
if($count_email > 0)
{
// Not available
echo 0;
}
else
{
// Available
echo 1;
}
}
?>
Try this..
//function to check username availability
check_availability = function(){
//get the username
var email = $('#email').val();
//declare the return value for the $.post call
var return_value = null;
// make the $.post call synchronous !!important
$.ajaxSetup({async: false});
//use ajax to run the check
$.post("checkEmail.php", { email: email },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
return_value = true;
}else{
//show that the username is NOT available
return_value = false;
}
});
// return the result (true or false)
return return_value;
// Validation
var mail = new LiveValidation('email', { validMessage: "Ok!" });
mail.add( Validate.Custom,{failureMessage:"E-mail is al in gebruik!",
against: function(){ return check_availability() }
});
This should work. I tested it. sort of... ha!
The problem was that you cannot return a value from within the scope of the $.post call. You must first declare the return variable outside the scope of the $.post call. Then you can assign the value of that variable from within the $.post. But also the $.post call must be set to "synchronous". ie - $.ajaxSetup({async: false});
If I'm not mistaken, ajax result would be a string. result == "1" not result == 1.
You could also do result == parseFloat(result)
I am trying to make this ajax request function work but netbeans is giving a warning that the following function does not always return a value. Can anyone please help.
function fpform(){
var response='';
var fpemail = $('#frgtpwd').val();
//var fpemail = document.getElementById('frgtpwd').value;
if (fpemail == ""){
$('span#fperror').text("insert your emal address");
//document.getElementById('fperror').innerHTML = "Insert your email address";
return false;
} else {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(fpemail)==false) {
$('span#fperror').text("Email address is not in valid format");
//document.getElementById('fperror').innerHTML = "Email address is not in valid format";
return false;
} else {
$("#loader").html('<img src="images/ajax-loader.gif" />');
$.post("forgot_password_process.php", {
email:fpemail
}, function(response){
response = response.trim();
}).success(function () {
if (response == 'yes'){
$("#fperror").html('<font color="green"><b>Your password has been reset now and emailed to you </b></font>');
$("#loader").hide('<img src="images/ajax-loader.gif" />');
return true;
} else {
alert("your email address was not found");
$("#loader").hide('<img src="images/ajax-loader.gif" />');
$("#fperror").html('<font color="black"><b> Email address was not found in database!</b></font>');
return false;
}
});
}
}
}
The return true; statement in your code is not returning from fpform. It is instead returning from the callback function given to .success(). By the time this function is executed, the outer function, fpform, has long since returned. The only way to "return" from a function using ajax is with a callback.
Before I give you any code, you've made a bunch of other mistakes:
Your email regex, /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, fails on my email address. + is a valid character as well. Consider not validating email addresses with regex.
$("#loader").hide('<img src="images/ajax-loader.gif" />') does not work. At all. You want $("#loader").empty()
The variable response you declare at the top is shadowed by your argument response in one of your anonymous functions, making response = response.trim() have no effect whatsoever.
function fpform(callback) {
var fpemail = $('#frgtpwd').val();
if (fpemail == ""){
$('span#fperror').text("insert your email address");
callback(false);
} else {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(fpemail)==false) {
$('span#fperror').text("Email address is not in valid format");
callback(false);
} else {
$("#loader").html('<img src="images/ajax-loader.gif" />');
$.post("forgot_password_process.php", {
email:fpemail
}).success(function(response) {
response = response.trim();
if (response == 'yes'){
$("#fperror").html('<font color="green"><b>Your password has been reset now and emailed to you </b></font>');
$("#loader").hide('<img src="images/ajax-loader.gif" />');
callback(true);
} else {
alert("your email address was not found");
$("#loader").hide('<img src="images/ajax-loader.gif" />');
$("#fperror").html('<font color="black"><b> Email address was not found in database!</b></font>');
callback(false);
}
}).error(function() { callback(false); });
}
}
}
You should return value after $.post(...).success(...);