$.post callback return strange data
Miguela Anthony’s Question:
I think this might be the cause of why my code is not working.. The ‘if(name.val().length > 3)’ is never can execute so I put an alert to test the returned data, this is what it look like :
my js
$(document).ready(function(){
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var passInfo = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var state = false;
name.keyup(validateName);
function validateName(){
if(name.val().length <= 3){
name.removeClass("valid");
nameInfo.removeClass("valid");
name.addClass("error");
nameInfo.addClass("error");
nameInfo.text("Minimum 4 characters!");
state = false;
}else{
if(name.val().length > 3){
var username=name.val();
$.post('validate.php',{names: username},function(data){
alert(data);
if(data!=0){
name.removeClass("valid");
nameInfo.removeClass("valid");
name.addClass("error");
nameInfo.addClass("error");
nameInfo.text("The username is already taken!");
state = false;
}else{
name.removeClass("error");
nameInfo.removeClass("error");
name.addClass("valid");
nameInfo.addClass("valid");
nameInfo.text("username available");
state = true;
}
});
}
}
}
return state;
//end
});
my PHP code :
<?php
$name = $_POST['names'];
$email = $_POST['emails'];
if($name !=""){
mysql_connect("localhost","root","") or die("Fail to connect to database");
mysql_select_db("reglog");
$uname = mysql_query("SELECT username FROM users WHERE username='$name'");
$count = mysql_num_rows($uname);
if($count !=0){
echo 1;
}else{
echo 0;
}
}
if($email !=""){
mysql_connect("localhost","root","") or die("Fail to connect to database");
mysql_select_db("reglog");
$useremail = mysql_query("SELECT email FROM users WHERE email='$email'");
$countemail = mysql_num_rows($useremail);
if($countemail !=0){
echo 1;
}else{
echo 0;
}
}
?>
It is throwing an warning
. Make a habit of checking if a index
is available in an array, thus removing possibilities of such error.
$email = isset($_POST['emails']) ? $_POST['emails'] : '';
or do not display any errors to suppress such warning (not recommended).
And as mentioned by Kai, you haven’t passed any variables as emails
.
$.post('validate.php',{ names: username, 'emails' : email }, ... }