I have a simple registration form that uses jQuery and Ajax to validate the user input. When the Ajax tries to do the server side validation of the e-mail address (for example) and connect to the database, it doesn't return a result via $msg
.
function checkUser () {
$search = mysql_query("SELECT * FROM users WHERE username = '" . $username . "'");
$match = mysql_num_rows($search);
if($match > 0) {
$msg .= 'Username already in use, please try another.';
}
}
Here is the JS:
function send(datastr) {
$.ajax({
type: "POST",
url: "./scripts/addmember.php",
dataType: "text",
data: datastr,
cache: false,
success: function(html) {
$("#errordiv").fadeIn("slow");
$("#errordiv").html(html);
//setTimeout('$("#errordiv").fadeOut("slow")',2000);
}
});
}
In your checkUser()
function you're using $msg
and $username
, which aren't defined. You either left those out or you are very new to programming.
In PHP, variables usually have only a single "scope". This means that a variable $msg
isn't accessible in a function, unless you define it there.
In javascript, this is valid :
var msg = "";
function appendToMsg(text) {
msg += text;
}
appendToMsg("test");
In PHP, this is not:
$msg = "";
function appendToMsg($text) {
$msg += $text;
}
appendToMsg("test");
This will throw a notice PHP Notice: Undefined variable: msg. The function appendToMsg
will only know $text
, not $msg
.
The correct PHP representation of the little JavaScript code is:
$msg = "";
function appendToMsg(&$msg, $text) {
$msg += $text;
}
appendToMsg($msg, "test");
More on variable scopes:
You need to echo
the output:
echo 'Username already in use, please try another.';
after you are setting text for the $msg variable, write this:
echo $msg;