views:

136

answers:

3

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.

A: 

How about having ajax.php return a bit of pre-formatted HTML and using the statechange_username function, which you've set to process the response, to stick it in a placeholder div/span?

By the way, why are you setting a session variable?

No Surprises
Session variable is used in the PHP code above
RPK
I agree with @No Surprises, try returning HTML instead of XML, unless you plan to use a library like JQuery
Anand
A: 

Hi,

I guess you are missing the statechange_username function, something like

function statechange_username() 
{ 
    if (http.readyState==4)
    { 
     document.getElementById(\"username_eixsts\").innerHTML=http.responseText;
    }
}
Anand
I don't think that anything is missing as the site is working fine except the colors that I desire.
RPK
+1  A: 

I'd do this using jQuery and have the PHP page return a code (0 for false, 1 for true) or similar. You can then use jQuery's addClass() method depending on the returned result, all in the javascript.

Matt Andrews
@Matt: Can you please illustrate?
RPK
Look for the jQuery Ajax documentation, and simply use it to run a POST/GET call to your php script. If the username exists, echo 1, if not, echo 0. Then in the 'success' parameter of the ajax call, you can interpret the response, eg: `if(response == 1) { $('#username').addClass('invalid'); // username exists } else { $('#username').addClass('valid'); // username is unique }`
Matt Andrews
I have tried a million combinations and can't get code formatting in comments to work, sorry.
Matt Andrews
@Matt: It's OK.
RPK