In my website home page, I have a new user registration Form. It contains a field "User Name". When the user enters the user name and the focus is pointed to another field, an AJAX code is executed that checks whether any user with the entered username already exists or not.
The AJAX code that I am using is this:
function toggle_username(userid) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
handle = document.getElementById(userid);
var url = 'ajax.php?';
if(handle.value.length > 0) {
var fullurl = url + 'do=check_username_exists&username=' + encodeURIComponent(handle.value);
http.open("GET", fullurl, true);
http.send(null);
http.onreadystatechange = statechange_username;
}
else
{
document.getElementById('username_exists').innerHTML = '';
}
}
The file "AJAX.PHP" called by the above code, is like this:
<?php
mysql_connect ('localhost', 'MyServer', 'user1');
mysql_select_db('globaldb');
$do = $_GET['do'];
switch($do) {
case 'check_username_exists':
if(get_magic_quotes_gpc()) {
$username = $_GET['username'];
}else{
$username = addslashes($_GET['username']);
}
$count = mysql_num_rows(mysql_query("SELECT * FROM `student_login` WHERE `username`='".$username."'"));
header('Content-Type: text/xml');
header('Pragma: no-cache');
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<result>';
if($count > 0) {
$_SESSION['UserExists'] = "true";
}else{
$_SESSION['UserExists'] = "false";
}
$_SESSION['UserExists'] = "false";
echo '</result>';
break;
default:
echo 'Error, invalid action';
break;
}
?>
In my registration form, just below the username input box, I want to define a section where in I can show the messages:
User with this name exists, or
Username is available.
In my home page, I am using following code:
<input name="username" type="text" id="username" onchange="toggle_username('username')" style="width:150px;" maxlength="40" size="22" >
<?PHP
if ($_SESSION['UserExists'] == "true")
{
echo "<div id='username_exists' style='font-size: 11px;font-weight: bold;color:red'>User with this name unavailable.</div>";
}
else
{
echo "<div id='username_exists' style='font-size: 11px;font-weight: bold;color:darkgreen'> User with this name is available </div>";
}
?>
The home page consists of the above code and the first code block (JavaScript) on top that I gave.
This code is not working. And I guess the reason is that I am have included the messages in the PHP block. Being server-side, it is not showing the messages.
Please let me know how to handle this issue. Whether to modify the JavaScript code that calls the AJAX or include something in the PHP.
Please also note that what actually I want is to show the messages in green or red color. If the user name is available, then green else in red color.