Checking if username is available before submitting a form

12,472

JS - JQUERY AJAX

$.ajax({ 
    url: 'register.php', data: {action: 'isUserNameTaken', params: [username]},
    type: 'post',
    success: function(data) {
        //Do Something
    }
});

PHP

<?php
function isUserNameTaken($username) {
    //Do Something;
}

if(!empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'isUserNameTaken':
            $username = '';

            if(!empty($_POST['params'])) {
                $username = $_POST['params'][0];
            }

            isUserNameTaken($username);

            break;
    }
}
?>

Share:
12,472
Mads Nielsen
Author by

Mads Nielsen

Updated on June 17, 2022

Comments

  • Mads Nielsen
    Mads Nielsen almost 2 years

    I want to check if the username is taken before the form is submitted.

    As far as I can understand I have to use AJAX to get data from my database in javascript. How do I send the username to the PHP file?

    This is my form:

    <form id="loginForm" action="register.php" method="post">
        <p>Register:</p>
        <p style="text-align: left;">Full name: <br><input type="text" name="name" required/></p>
        <p style="text-align: left;">Email: <br><input type="text" name="email" required/></p>
    
        //Username
        <p style="text-align: left;">Username: <br><input id="username" type="text" name="username" onkeyup="validateUsername(value);" required/></p>
        <span id="usernameError" style="display:none;border:1px solid red;">Username can only contain a-z, 0-9 and must be at least 6 characters loong</span>
        <span id="usernameTaken" style="display:none;border:1px solid red;">Username taken</span>
    
        <p style="text-align: left;">Password: <br><input type="password" name="password" required/></p>
        <input type="submit" value="Register">
    </form>

    This is the validateUsername() function:

    function validateUsername(username) {
        var re = /[a-zA-Z0-9]/;
        alert(username.length);
        if(re.test(username) && username.length > 5) {
            document.getElementById('username').style.backgroundColor = "green";
            document.getElementById('usernameError').style.display= "none";
            --error;
        } else {
            document.getElementById('username').style.backgroundColor = "red";
            document.getElementById('usernameError').style.display= "block";
            ++error;
        }
        //here i want to check if the user name is taken
    }

    If the username is taken, I want to display the 'usernameTaken' span. Otherwise, I want to hide it.

    Here is the PHP file that checks if the username is already in the database:

    <?php
    session_start();
    define('DB_NAME', 'madsanker_dk_db');
    define('DB_USER', 'madsanker_dk');
    define('DB_PASSWORD', 'MyPassword');
    define('DB_HOST', 'mysql43.unoeuro.com');
    
    $link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
    
    if (!$link) {
        die('Could not connect: ' .mysqli_error());
    }
    
    $db_selected = mysqli_select_db( $link, DB_NAME);
    
    if (!$db_selected) {
        die('Could not connect: ' .mysqli_connect_error());
    }
    
    $username = //The username;
    $username = mysqli_real_escape_string($link,$username);
    
    $sql = "SELECT * FROM mainLogin WHERE username = '$username'";
    
    $result = mysqli_query($link, $sql);
    $count = mysqli_num_rows($result);
    
    if($count == 0) {
        //if the username is NOT taken
        return true;
    } else {
        //if the username IS taken
        return false;
    }
    mysqli_close($link);
    ?>

    How is this done?

  • mehulmpt
    mehulmpt about 8 years
    Why would you like to add jQuery for just a simple ajax request when it is not used anywhere else?
  • xmisd
    xmisd about 8 years
    Well, by using onkeyup, you could check the database every time the user types something into it, Mads Anker doesnt want to submit the form and then check the username right? So this is a way that could be done.
  • mehulmpt
    mehulmpt about 8 years
    That would be a terrible idea @Tom. You wouldn't like to DoS your own server. SQL queries can be a bit expensive and when done like 10s of times a second by every user out of thousands of users on site (lets assume), it'll be fatal to server.
  • Mads Nielsen
    Mads Nielsen about 8 years
    @MehulMohan What do you suggest i do without using jQuery?
  • mehulmpt
    mehulmpt about 8 years
    @MadsAnkerNielsen use XMLHttpRequest.
  • xmisd
    xmisd about 8 years
    Hmm you are right, but what if the ajax is fired lets say 2 seconds after the user types something into input? Would that be any better?
  • Mads Nielsen
    Mads Nielsen about 8 years
    Thanks Guys. I will go look up how to use "XMLHttpRequest".
  • Gromski
    Gromski about 8 years
    isset && !empty is nonsensical, use just !empty.
  • Ibrahim Ahmed
    Ibrahim Ahmed about 8 years
    @deceze Thanks for your comment, I edited my answer though to be honest am not a PHP developer i just found the question did a quick research and wanted to share the results i came up with :)