Chech Username(Email) Availability with LiveValidation.Custom Function - javascript

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)

Related

How come Ajax response is different?

I can't find the reason why my ajax response is different when I console.log the response. Any ideas?
Page1 is used in account update form while page2 is used in registration form.
page1.js:
function ajaxCheckDupEmail(){
if(valid_email === true){
return $.ajax({
type:'POST',
url:'ajax/page1.php',
data:{ 'email': email, 'email_login': email_login },
success:function(response){
//some code
}
});
}else{
//other code
}
}
$.when(ajaxCheckDupEmail()).done(function(a1){
console.log(a1);
if(a1[0] === 'false'){
//submitting form
//some code
}
});
NOTE: email and email_login is a js var where I store userinput in, I used valid_email to check if email is valid
page1.php:
if(isset($_POST["email"]) && !empty($_POST["email"])){
$email = trim_strip_data($_POST["email"]);
$email_login = trim_strip_data($_POST["email_login"]);
$prep_data_email = $db->prepare("SELECT email FROM user WHERE email = :email");
$prep_data_email->execute(array(":email" => $email));
$row_count = $prep_data_email->rowCount();
if($row_count === 1 && $email !== $email_login){
echo "true";
}else{
echo "false";
}
}
NOTE: trim_strip_data() is a custom function to trim white spaces although I don't think it is necessary in this case
page2.js:
function ajaxCheckDupEmail(){
if(valid_email === true){
return $.ajax({
type:'POST',
url:'ajax/page2.php',
data:{ 'email': email },
success:function(response){
// some code
}
});
}else{
//other code
}
}
function ajaxCheckDupUsername(){
if(username !== ""){
return $.ajax({
type:'POST',
url:'ajax/page2.php',
data:{ 'username': username },
success:function(response){
// some code
}
});
}else{
//other code
}
}
$.when(ajaxCheckDupUsername(), ajaxCheckDupEmail()).done(function(a1, a2){
console.log(a1);
console.log(a2);
if(a1[0] === 'false' && a2[0] === 'false'){
//submitting form
//some code
}
});
NOTE: email is a js var where I store userinput in, I used valid_email to check if email is valid
page2.php:
if(isset($_POST["email"]) && !empty($_POST["email"])){
$email = trim_strip_data($_POST["email"]);
$prep_data_email = $db->prepare("SELECT email FROM user WHERE email = :email");
$prep_data_email->execute(array(":email" => $email));
$row_count = $prep_data_email->rowCount();
if($row_count === 1){
echo "true";
}else{
echo "false";
}
}
if(isset($_POST["username"]) && !empty($_POST["username"])){
$username = trim_strip_data($_POST["username"]);
$prep_data_username = $db->prepare("SELECT username FROM users WHERE username = :username");
$prep_data_username->execute(array(":username" => $username));
$row_count = $prep_data_username->rowCount();
if($row_count === 1){
echo "true";
}else{
echo "false";
}
}
NOTE: trim_strip_data() is a custom function to trim white spaces although I don't think it is necessary in this case
The problem is I get 2 different response results (depending on result true/false).
In page1.js I get:
true
In page2.js I get:
true,success,[object Object]
true,success,[object Object]
It looks like I get an response object in page2.js but why I don't get one in page1.js?
https://api.jquery.com/jquery.when/#jQuery-when-deferreds
You are dealing with promises, and a promise always returns a promise.
So I would double check page1 isn't returning the object too.
E.g. open dev tools and run the following;
$.when().done(function( x ) { alert('done')});
you will see it returns an object, this is the promise.
but for
true,success,[object Object]
I don't see where success is coming from, are you missing some code?
On a side note...
if(valid_email === true)
is the same as
if(valid_email)
sorry, it was just bugging me.

return false not working in jQuery ajax

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.

JavaScript function always run bottom code

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;
}
});
}

Validation of registration form with AJAX and JSON

I have a Username field in my registration form. When the user hits the Submit button, it should check if the username is not empty and that such username doesn't exist yet. So I have these functions:
function register() {
var userName = checkIsUsernameExist();
var passwordMatch = checkPasswordMatch();
if(userName && passwordMatch){
$.getJSON("inc/API.php",
{
command : "register",
username : $("#txtNewUsername").attr("value"),
password : $("#txtNewPassword").attr("value"),
email : $("#txtEmail").attr("value"),
phone : $("#txtPhone").attr("value")
},
function ()
{
$("#divIsRegFormValid").removeClass("registrationFormAlert");
$("#divIsRegFormValid").addClass("registrationFormConfirm");
$("#divIsRegFormValid").html("Thank you for registering!");
}
);
} else {
$("#divIsRegFormValid").removeClass("registrationFormConfirm");
$("#divIsRegFormValid").addClass("registrationFormAlert");
$("#divIsRegFormValid").html("Some errors occured. Please register again.");
}
}
function checkIsUsernameExist(){
if($("#txtNewUsername").attr("value") == "") {
$("#divIsUsernameExist").html("");
return false;
} else {
$.getJSON("inc/API.php",
{
command : 'isUsernameExist',
username : $("#txtNewUsername").attr("value")
}).done(
function(result)
{
if (result != true){
$("#divIsUsernameExist").removeClass("registrationFormAlert");
$("#divIsUsernameExist").addClass("registrationFormConfirm");
$("#divIsUsernameExist").html("This username is available!");
return true;
} else {
$("#divIsUsernameExist").removeClass("registrationFormConfirm");
$("#divIsUsernameExist").addClass("registrationFormAlert");
$("#divIsUsernameExist").html("This username is not available!");
return false;
}
});
}
}
At this moment I only receive False if the username is empty, and if it's not - I get Undefined (checked it with some Alert commands). So how can I make it work and return True or False if the username is entered and it's been checked if such username already exist or not?
Thank you!
.val() is prefered $("#txtEmail").attr("value") => $("#txtEmail").val() ;)
You get undefined probably because there is no value attribute in your html use $('#txtEmail').val() instead.

Trouble using jQuery post inside non jQuery function

I have the following script inside a HTML page:
<script>
function Test(){
alert("i got here");
var username = document.registration_form.username.value;
alert(username);
$.post("checkname.php", { name: username }, function(data) {
alert("and here");
alert(data);
if (data = "0"){
alert('That username is already in use, please choose another');
return false;
};
if (data = "1") {
return true;
};
});
};
</script>
I'm trying to get the function test to return true or false if a username is already in my database.
checkname.php contains the following:
<?
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_POST['name'];
$sql="SELECT * FROM members WHERE username='".$myusername."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count >= 1){
echo "0";
}
else {
echo "1";
}
?>
I've tried hardcoding a name and running the PHP and it works fine.
For some reason though when I run Test() the first 2 alerts come through fine, showing me the username enetered, but none of the subsequent alerts appear.
Oooo and jQuery has been added in the header like so:
<script src="create/js/jquery-1.4.4.min.js" type="text/javascript" ></script>
<script src="create/js/jquery-ui-1.8.7.custom.min.js" type="text/javascript"></script>
Any help much appreciated :)
First of all, your return statements from the callback to $.post will not return from your Test() function. You should call Test with a callback function that deals with the data from the server, something like this:
function Test(username, callback) {
$.post("checkname.php", {name: username}, callback);
}
Test(document.registration_form.username.value, function(data) {
if(data == "0") {
// Do something
} else {
// Do something else
}
});
Brad is also correct about the comparison - you're currently assigning "0" to data. You should get the alerts though, I think, even with the other errors. Maybe you need the absolute path to the checkname.php script? E.g. "/checkname.php" (note the slash)?
Off-hand, you should be using == for comparison in javascript. A single = is an assignment, == is a comparison. So having said that, if (data = "0"){ would become if (data == "0"){.
Other than that, I don't see anything too fishy. You're allowed to use jQuery functions within "traditional" javascript function(){}'s.
Also, make sure you sanitize the input from the $_POST['name'] using something like mysql_real_escape_string.
The problem may be that the PHP script is returning a new line before or after it prints 0 or 1. So the string returned wouldn't equal "0" or "1".
Try to change it to output JSON instead.
if($count >= 1){
$ret = 0;
}
else{
$ret = 1;
}
echo json_encode(array('status' => $ret));
And then change your $.post to:
$.post("checkname.php", { name: username }, function(data) {
alert("and here");
alert(data);
if(data.status = 0){
alert('That username is already in use, please choose another');
}
if(data.status = 1) {
alert('That username is not already in use');
}
}, 'json');
NOTE: The return false and return true don't do anything. You cannot return from an AJAX call.

Categories