Reputation: 551
I'm a long time lurker and this is my first post so go easy on me...
so I'm fairly new to Javascript, I'm going to get around to jQuery eventually but for now I'm sticking to regular Javascript.
I've created a website in PHP and now I'm trying to setup some client side validation.
So after a little research on these forums I've discovered that it isn't that easy to get hold of responseText because of it's asynchronous nature. So I looked into call backs but I'm having a lot of trouble setting them up. I've managed to set it up but it keeps returning the entire html page instead of just the echoed string.
function checkName(usernameString, callback) {
//
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","checkName.php?q="+usernameString,true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("uMess").innerHTML=xmlhttp.responseText;
callback(xmlhttp.responseText);
}
}
//xmlhttp.open("GET","checkName.php?q="+usernameString,true);
xmlhttp.send();
}
function validateUsername(usernameString) {
var valid = true;
checkName(usernameString,function(err,response){
if (err) {
alert('Error: ' + err);
} else {
alert('Response: ' + response);
}
});
.....
Would someone mind pointing out where I'm going catastrophically wrong?? Thanks in advance guys :)
Also here's the PHP file which checks if the username is taken or not
<?php
include_once 'header.php';
$userName = $_GET['q'];
if ( strlen($userName) < 6 ){
$response = "Too Short!";
echo $response;
}
else{
$query = "SELECT user FROM temporaryusers WHERE user='$userName'";
$result = mysql_query($query);
if(mysql_num_rows($result))
{
$response="Taken";
echo $response;
}
else{
$response="Available";
echo $response;
}
}
?>
Upvotes: 1
Views: 76
Reputation: 360762
You're calling your callback with:
callback(xmlhttp.responseText);
^^^^^^^^^^^^^^^^^^^^--- one parameter
but the function is defined as
checkName(usernameString,function(err,response){
^^^^^^^^^^^--- two params
so your responsetext is actually going into the err
variable. You're simply passing back a string from the PHP script, so err
is ALWAYS going to be set and true.
Upvotes: 2