Welcome folks today in this blog post we will be building a username availability checker in php using ajax and mysql database. All the example code of the application is shown below.
Get Started
In order to get started you need to first of all download the Xampp Control Panel and start the Apache Server and MySQL Database as shown below
Now you need to create the database user_system inside the phpmyadmin area as shown below
Now we need to create the MySQL Table inside the phpmyadmin area go the sql section of the dashboard and execute the below sql query as shown below
1 2 3 4 5 6 |
CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(70) NOT NULL, `fullname` varchar(80) NOT NULL, `password` varchar(80) NOT NULL ); |
Here you can see we have the users table in this we have four columns
id is the primary key of the table which will be auto incremented
username is the column which will store the actual username
fullname is the column which will store the fullname
password is the column which will store the password
Inserting Dummy Values in Users Table
Now you can enter some dummy values inside the users table for testing the application as shown below
After that we will be making the connection to the mysql database in php. So for that make a config.php
file inside the root directory of your project folder and copy paste the below code
config.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $host = "localhost"; /* Host name */ $user = "root"; /* User */ $password = ""; /* Password */ $dbname = "user_system"; /* Database name */ // Create connection $con = new mysqli($host, $user, $password, $dbname); // Check connection if ($con->connect_error) { die("Connection failed: " . $con->connect_error); } |
So here you need to replace the hostname which is localhost in this case and then username,password and the database name of your application. After that we are passing all these details to the mysqli constructor.
If any error takes place we are exiting the application using the die method
Now we need to make an index.html
file inside the root directory
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>How to check username availability using JavaScript and PHP</title> </head> <body> <div> <input type="text" id="txt_username" name="txt_username" placeholder="Enter Username" maxlength='60' onkeyup="checkUsername(this.value);" /> <!-- Response --> <div id="uname_response" ></div> </div> </body> </head> </html> |
So here in this html code we have a simple input field which will hold the username which will be entered by the user and then we also have the span tag where we will be showing the dynamic colorful alert message to the user whether the user is available or not.
Sending AJAX Request to PHP Script
Now we will writing the javascript code where we will be using some ajax to send a post request to php script where we will be checking whether the passed username is already present inside the mysql database or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
function checkUsername(username){ var usernameRegex = /^[a-zA-Z0-9]+$/; if(usernameRegex.test(username)){ document.getElementById('uname_response').innerHTML =""; if(username.length > 4){ // AJAX request var xhttp = new XMLHttpRequest(); xhttp.open("POST", "ajaxfile.php", true); xhttp.setRequestHeader("Content-Type", "application/json"); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Response var response = this.responseText; document.getElementById('uname_response').innerHTML = response; } }; var data = {username: username}; xhttp.send(JSON.stringify(data)); } }else{ document.getElementById('uname_response').innerHTML = "<span style='color: red;'>Please enter valid value</span>"; } } |
This function will get called as soon as user starts typing inside the text field and every time called on key stroke of the user. We have attached a keyup event handler to the input field in the html if you closely look where we passed this function name and also passed the username as an argument.
And in this we are using ajax post request to pass that username to the php script and parsing the response which is coming back from the php script and depending upon the response it is showing either username available in green color or not available in red color.
Writing the PHP Script
Now we will be writing the actual php script which is called ajaxfile.php
which is responsible for actually checking whether the passed username is available or not.
ajaxfile.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php include 'config.php'; // Read POST data $data = json_decode(file_get_contents("php://input")); if(isset($data->username)){ $username = mysqli_real_escape_string($con,$data->username); $query = "select count(*) as cntUser from users where username='".$username."'"; $result = mysqli_query($con,$query); $response = "<span style='color: green;'>Username is Available.</span>"; if(mysqli_num_rows($result)){ $row = mysqli_fetch_array($result); $count = $row['cntUser']; if($count > 0){ $response = "<span style='color: red;'>Username is Not Available.</span>"; } } echo $response; } |
Here guys in the above php code we are first of all using the json_decode() method to get the username which is passed from ajax.
And then basically in the next step it is writing a simple sql query where it is checking whether the username is available or not. And whether the count value is 0 or not it is compared in the if statement. Then it is returning the appropriate message back to the client.
Now guys if you open the app inside the browser the result will look like this as shown below