article

Monday, March 7, 2022

PHP PDO Mysql Check username availability with Jquery AJAX

PHP PDO Mysql Check username availability with Jquery AJAX

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css
https://getbootstrap.com/docs/5.0/components/modal/

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
checkusername.php
//checkusername.php
<!doctype html>
<html>
 <head>
<title>PHP PDO Mysql Check username availability with Jquery AJAX </title>
<link rel = "stylesheet" type = "text/css" href = "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />		
<script src = "https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>	
</head>
<body>
	<div class="container">
		<div class="row"><p><h1>PHP PDO Mysql Check username availability with Jquery AJAX </h1></p>
			<label class="form-label">Enter UserName</label>
			<input type="text" id="txt_username" class="form-control" name="txt_username" placeholder="Enter Username">
			<!-- Response -->
            <div id="uname_response" ></div>
		</div>
	</div>
    <script type='text/javascript'>
            $(document).ready(function(){

                $("#txt_username").keyup(function(){

                    var username = $(this).val().trim();

                    if(username != ''){

                        $.ajax({
                            url: 'ajaxfile.php',
                            type: 'post',
                            data: {username:username},
                            success: function(response){
                                console.log(response);
                                // Show response
                                $("#uname_response").html(response);

                            }
                        });
                    }else{
                        $("#uname_response").html("");
                    }

                });

            });
	</script>
</body>
</html>
ajaxfile.php
//ajaxfile.php
<?php

$server = "localhost";
$username = "root";
$password = "";
$dbname = "testingdb";

// Create connection
try{
   $conn = new PDO("mysql:host=$server;dbname=$dbname","$username","$password");
   $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
   die('Unable to connect with the database');
}

if(isset($_POST['username'])){
	$username = $_POST['username'];

	// Check username
	$stmt = $conn->prepare("SELECT count(*) as cntUser FROM users WHERE username=:username");
	$stmt->bindValue(':username', $username, PDO::PARAM_STR);
	$stmt->execute(); 
	$count = $stmt->fetchColumn();
	//echo $count;
	
	if($count == 0){
		$response = "<span style='color: green;'>Available.</span>";	
	}else{
		$response = "<span style='color: red;'>Not Available.</span>";
	}	
	
	echo $response;
	exit;
}

Related Post