PHP AJAX Programming

by Vincy. Last modified on May 17th, 2023.

AJAX can be expanded as  Asynchronous Javascript and XML and it is a method to request a server-side script to execute via javascript. This request is generated in a Javascript function and sent to a PHP file.

On the server side, the PHP file receives and processes the request passed through an AJAX call and sends a response. The client-server communication will be done asynchronously. After getting a response from the PHP file, we can update a particular web page component and avoid page refresh.

AJAX can be implemented by using various libraries and APIs. In this tutorial, I use XMLHttpRequest API to send an AJAX request for executing the PHP login script.

After getting the response from the PHP, the AJAX code checks the status and shows the authentication result on the web page without refreshing it.

ajax program example for php login

Login Form with AJAX Button Handler

The following code shows a  login form with the User Name and the Password fields. On clicking the Login button, it calls a Javascript AJAX function. This function will send the login field values to PHP to process user authentication.

It contains a target DIV container where authentication results will be shown to the user by the AJAX function without refreshing log-in page.

<div id="output" class="phppot-container tile-container text-center">
    <div id="messageBoxId"></div>
    <form action="" method="post" id="frmLogin">
        <h2>Enter Login Details</h2>
        <div class="row">
            <label class="text-left" for="login">Username</label> <input name="userName" id="userName" type="text" class="full-width">
        </div>
        <div class="row">
            <label class="text-left" for="password">Password</label> <input name="password" id="password" type="password" class="full-width">
        </div>
        <div class="row">
            <input type="button" name="login" value="Login" class="full-width" id="login" onClick="callLogin();"><span><img src="loader.gif" id="loader-img" class="display-none"></span>
        </div>
    </form>
</div>

Sending Login Request via Javascript AJAX Function

In this Javascript function, we create an AJAX login request using an XMLHttpRequest instance. Since old browsers are not supporting this API, we can create ActiveXObject.

This function sends the user’s login details to login.php as the “GET” requests. This function will show a welcome screen if the user is authenticated successfully. Otherwise, an error message will be displayed on the login form.

If you want a different login form layout, the linked article gives HTML for multiple login themes.

The AJAX will make all these changes instead of reloading the page.

function callLogin() {
    $("#loader-img").show();
    $("#login").hide();
    var userName = document.getElementById("userName").value;
    var password = document.getElementById("password").value;
    xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.onreadystatechange = function () {
        if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
            var response = xmlHttpRequest.responseText;
            if (response > 0) {
                var welcome_message = '<h4>Welcome, You have successfully loggedin!</h4>';
                document.getElementById("output").innerHTML = welcome_message;
            } else {
                $("#loader-img").hide();
                $("#login").show();
                document.getElementById("messageBoxId").innerHTML = "Invalid Credentials";
                document.getElementById("messageBoxId").className = "validation-message";
            }
        }
    }
    xmlHttpRequest.open("GET", "login.php?userName=" + userName + "&password=" + password, true);
    xmlHttpRequest.send();
}

Database script

Import this database script into your server. It is created for this AJAX login example to validate the user login data with the database.

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `userName` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL
);

INSERT INTO `users` (`id`, `userName`, `password`) VALUES
(1, 'admin', '$2a$10$0FHEQ5/cplO3eEKillHvh.y009Wsf4WCKvQHsZntLamTUToIBe.fG');

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

PHP Login Script with MySQL.

The following PHP code receives AJAX requests and processes authentication. It searches the user database for the login details passed by the AJAX call. If a match is found, it will return true as a response.

<?php
if (count($_GET) > 0) {
    $conn = mysqli_connect("localhost", "root", "", "login_ajax");   
    $query = "SELECT * FROM users WHERE userName=?";
    $stmt = $conn->prepare($query);
    $username = $_GET["userName"];
    $password = $_GET["password"];
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $isSuccess = 0;
    if (is_array($row)) {
        $isSuccess = 0;
        $hashedPassword = $row["password"];
        if (password_verify($password, $hashedPassword)) {
            $isSuccess = 1;
        }
        if($isSuccess == 1){
            $count = mysqli_num_rows($result);
            print $count;
        }
    }
}
?>

Download

Comments to “PHP AJAX Programming”

Leave a Reply to Vincy Cancel reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page