The first thing I would do (aside from removing your MySQL 'root' user password from the code you've posted) is to eliminate all those echo statements and just put straight markup and JS in there. Your httpd server and PHP parser will thank you, I will thank you, and it will make it alot easier to work with and edit the JS. Similarly, your form code at the bottom of the script should be straight markup without PHP intervention at all.
Now, you're actually using the script you've loaded with the form to do the database call? Why not use a separate PHP script to do that? This page could be straight markup and JS with no PHP at all if you separate the two. I'd wager that's the hangup here.
Your PHP script should be something simple like
PHP Code:
<?php
// checkuser.php
if ( empty($_GET['username']) ) { echo 'FAILED'; exit; }
// db connect code here
// validate and escape username input
if ( ctype_alnum($_GET['username']) && strlen($_GET['username']) <= 25 ) {
$u= mysql_real_escape_string( $_GET['username'] );
$sql= "SELECT COUNT(*) AS valid_user FROM table WHERE username='{$u}'";
if ( mysql_result( mysql_query($sql), 0 ) !== 0 ) {
echo "This username is taken";
} else echo "This username is available";
}
?>
Your jQuery code calls this script using a GET method request and then handles the response.
Perhaps an ideal method would be to use a UNIQUE index on the `username` column (which you should do anyway), and then actually use a POST request to insert a record with the requested username. If the query fails due to the UNIQUE index constraint, you report the username is taken and try again. If not, you simply force the user to complete the registration and perform an UPDATE with the rest of the form data.