Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts

    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.
    Last edited by d'Anconia; 09-07-2012 at 01:25 AM.
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,346
    Thanks
    11
    Thanked 589 Times in 570 Posts
    this is always true:
    Code:
    if (usernameSpan.textContent !== undefined) {
    if it is without text, it will be null or "", not undefined, and the "!==" means it's picky about those.

    try hitting all 3 while saving keystrokes:

    Code:
    if (usernameSpan.textContent) {
    Last edited by rnd me; 09-07-2012 at 06:49 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #3
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts
    If I remember correctly that line is to figure out whether or not IE is being used or a different browser.
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •