AndrewMRiv
AndrewMRiv

Reputation: 165

Use AJAX and PHP to "Alert" the user if the username exists on the same page?

I have found many AJAX scripts that do a live check on if the username exists in a MySQL database. For example, most will maybe show a green check image if it does not exist or a red x if it does already exist.

I am interested in a slightly different method for this form.

Users fill out a 10 question quiz and then are taken to a user registration form. I only want to insert the user's answers into the database if they complete the quiz.

Currently, if a user enters a username or email that already exists, they will receive an error on the next page and be told to be go back only to find that the form has been reset.

That is why I want the information validated all on the same page.

Upon clicking the submit button, a javascript function is called that verifies a few things such as if the user has entered a date of birth, has not left a form blank, if passwords match, etc.

It returns false if any of the criteria is not met so that the form does move to the next page unless all of the functions return true.

Here is what it looks like.

function checkForm() {

if (checkUser() && checkPassword() && checkMonth() && checkDay() && checkAddress() && checkYear()) {
    document.getElementById("quizForm").method="post";
    document.getElementById("quizForm").action="register.php";
}
else {
    return false;
}
}

I am interested in creating a username/email check function that uses ajax to access a php page that searches the database and returns true or false to javascript on if the username/email exists in the database.

That way, I can just use the old javascript alert to say if a username/email exists and then return false so that the form is not submit.

This is an example of how I am writing the functions for this:

function checkPassword() {
var pass1 = document.getElementById("pass").value;
var pass2 = document.getElementById("c_pass").value;
var pass1l = pass1.length;

if (pass1l < 5) {
    alert("Please create a password that is longer than 5 characters.");
    return false;
}
else {
    if (pass1 != pass2) {   
        alert("Your passwords do not match.");
        return false;
}
    else {
        return true;
    }
}

}

Can anyone point me in the right direction for this? I have been searching around but have not found anything that is this specific.

Thank you.

Upvotes: 1

Views: 5042

Answers (1)

Fredrik
Fredrik

Reputation: 764

You could AJAX Post on change event of the <input> where the user enters the username. Consider the example below I quickly put together. It assumes you have the database table users with columns id and username. It also assumes you have a file check.php connecting to this database table with a MySQLi connection in the variable $mysqli. When the input changes, it will call check.php, with the only data being the username entered. Depending on the response, it will update <span id="info">.

HTML:

<input id="username" type="text" /><span id="info">Exists/Does not exist</span>

Javascript(jQuery):

$(function() {

        $("#username").on("change", function() {

            var data = "user="+$("#username").val();

            $.ajax({
                type: 'POST',
                url: 'check.php',
                data: data,
                dataType: 'json',
                success: function(r)
                {
                    if(r=="1")
                    {
                        //Exists
                        $("#info").html("Username already exists");
                    }else{
                        //Doesn't exist
                        $("#info").html("Username available!");   
                    }
                }
            });

        });

});

PHP(check.php):

$user = $_POST['user'];

    if($stmt = $mysqli->prepare("SELECT id FROM users WHERE username = ?"))
    {
        $stmt->bind_param('s', $user);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($id);
        $stmt->fetch();
        if($stmt->num_rows>0)
        {
            echo "1";
        }else{
            echo "0";   
        }
    }

I'm using similar functionality on my current project, and it works fine. Especially with local files as response time is improved!

(Reserved for typos, was in a rush-ish)

Hope this helped.

Upvotes: 2

Related Questions