View Single Post
Old 09-07-2012, 01:23 AM   PM User | #1
d'Anconia
Regular Coder

 
d'Anconia's Avatar
 
Join Date: Jan 2010
Location: Tempe, AZ
Posts: 142
Thanks: 15
Thanked 5 Times in 5 Posts
d'Anconia is an unknown quantity at this point
Using AJAX to Check Database for Available Usernames

Okay so I am relatively new to JavaScript but I am pushing forward trying to get AJAX to work on my prototype website for the first time. Specifically I want to have my registration page use AJAX to notify the user of whether their desired username is available in our system or not.

I am familiar with HTML / CSS so I don't think the issue is in there, and am familiar enough with PHP and MySQL but not necessarily how PHP interacts with Javascript via AJAX.

Here is my code, emphasis on the Javascript portion (and PHP portion) because those are the parts that I am most unfamiliar with:

Code:
<tr>
        <td class="form_left"><label for="username">Username:</label></td>
        <td class="form_right"><input type="text" id="username" name="username" size="25" maxlength="25" 
            value="<?php if (isset($_POST['username'])) {echo $_POST['username'];} ?>" onKeyUp="verifyUsername()" /><span id="usernameSpan"
                style="color:red;">*</span></td>
    </tr>
...
<script src="/js/register.js"></script>
    <script src="/js/ajax.js"></script>
Here is my PHP code:

PHP Code:
require_once ($_SERVER["DOCUMENT_ROOT"] . '/includes/config.inc.php');

//
if (isset ($_POST['enteredUsername'])) {
    
$submitted_username $_POST['enteredUsername'];
     require_once (
MYSQL); // Connect to the db.
    
}
$check_username_query "SELECT username FROM users WHERE username = $submitted_username";
$r mysqli_query ($dbc$check_username_query) ;
if (
mysqli_num_rows($r) == 0) {
    echo 
'VALID';
}
else {
    echo 
'INVALID';

And here is my Javascript code:

Code:
function verifyUsername() {
    'use strict';
    
    //Get a reference (get element by ID) to the entered username value:
    var ajax = getXMLHttpRequestObject();
    
    var enteredUsername = U.$('username');
    var usernameSpan = U.$('usernameSpan');
    // Validate the first name:
	if (/[a-zA-Z0-9._-]{1,25}$/i.test(username.value)) { //tested true in console
                if (usernameSpan.textContent !== undefined) {
                    usernameSpan.textContent = "";
                    
                    
                }
                else {usernameSpan.innerText = "";}
                
                //Begin the AJAX request
                
                ajax.onreadystatechange = function() {
                    if (ajax.readyState == 4){
                        //Check the status code:
                        if ( (ajax.status >= 200 && ajax.status < 300)
                        || (ajax.status == 304) ) {
                        if (ajax.responseText == 'VALID') {
                            if (usernameSpan.textContent !== undefined) {
                                usernameSpan.textContent = "Username available";
                            }
                            else {usernameSpan.innerText = "Username available";}
                            }
                        else {
                            if (ajax.responseText == 'INVALID'){
                                 
                            if (usernameSpan.textContent !== undefined) {
                                usernameSpan.textContent = "Username not available";
                            }
                            else {usernameSpan.innerText = "Username not available";}
                                }   
                            }
                            }
                        }
                    };
        
                    ajax.open('POST', 'resources/verifyusername.php', true);
                    ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    var data = 'enteredUsername=' + encodeURIComponent(username.value);
                    ajax.send(data);
                        
                }
                
	 else {
		if (usernameSpan.textContent !== undefined) {
                    usernameSpan.textContent = "Username must be 25 characters or less, contain only \n\
                        numbers, letters, '.', '_', and '-'.        ";
                    }
                else {usernameSpan.innerText = "Username must be 25 characters or less, contain only \n\
                        numbers, letters, '.', '_', and '-'.";
                    }
                
                }
    
    
} //End of verifyUsername() function
As of right now when I enter a username it changes the asterisk to a blank spot. This means that my PERL regular expression is at least passing.



If I can at least narrow down the error to whether it's the PHP or Javascript code causing the issue then that will make it much easier to eventually find and fix the problem. Any help would be greatly appreciated! Once I get this AJAX thing down the first time it will make all subsequent attempts much easier because I will have a template to base my attempts off of. I have been dabbling in the Developer's Console in Chrome which at least shows verifyusername.php being initiated by register.js but not much more info.
__________________
Powerful ideas for all lovers of personal and political freedom:
Freedomain Radio
Free Talk Live

Last edited by d'Anconia; 09-07-2012 at 01:25 AM..
d'Anconia is offline   Reply With Quote