PHP AJAX Programming

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. In server side, PHP file it receives and processes the request passed through an AJAX call and send a response. The client-server communication will be done in an asynchronous way. After getting a response from the PHP file, we can update a particular component of a web page and avoid page refresh. 

AJAX can be implemented by using various libraries and API. In this tutorial, I am using XMLHTTPRequest API to send an AJAX request for executing PHP login script. After getting the response from the PHP, the AJAX code checks the status and show authentication result in the web page without refreshing it.

login-form

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 AJAX function without refreshing login page.

<div id="output">
	<div id="messageBoxId"></div>		
	<form action="" method="post" id="frmLogin">
		<div class="field-group">
			<div><label for="login">Username</label></div>
			<div><input name="userName" id="userName" type="text" class="input-field">
		</div>
		<div class="field-group">
			<div><label for="password">Password</label></div>
			<div><input name="password" id="password" type="password" class="input-field"> 
		</div>
		<div class="field-group">
			<div><input type="button" name="login" value="Login" class="form-submit-button" onClick="callLogin();"></span></div>
		</div>       
	</form>
</div>

Sending Login Request via Javascript AJAX Function

In this Javascript function we create AJAX login request by using XMLHttpRequest instance. Since old browsers are not supporting this API, we can create ActiveXObject. This function sends user’s login details to login.php as the “GET” requests. If the user is authenticated successfully, then this function will show welcome screen. Otherwise, an error message will be shown on top of the login form. All these changes will be made by the AJAX instead of reloading the page.

<script>
function callLogin(){
	var userName = document.getElementById("userName").value;
	var password = document.getElementById("password").value;
	xmlHttpRequest=new XMLHttpRequest();
	// For Older browsers
	// xmlHttpRequest=new ActiveXObject("MSXML2.XmlHttp");
	xmlHttpRequest.onreadystatechange=function() {
		if (xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200) {
			var response = xmlHttpRequest.responseText;
			if(response > 0) {
				var welcome_message = '<p class="welcome-message">Welcome, You have successfully loggedin!</p>';
				document.getElementById("output").innerHTML = welcome_message;
			} else {
				document.getElementById("messageBoxId").innerHTML="Invalid Credentials";
				document.getElementById("messageBoxId").className="error-message";
			}
		}
	}
	xmlHttpRequest.open("GET","login.php?userName="+userName+"&password="+password,true);
	xmlHttpRequest.send();
}
</script>

PHP Login Script with MySQL.

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

<?php
	if(count($_GET)>0) {
		$conn = mysqli_connect("localhost","root","","blog_samples");
		$result = mysqli_query($conn,"SELECT * FROM users WHERE userName='" . $_GET["userName"] . "' and password = '". $_GET["password"]."'");
		"SELECT * FROM users WHERE userName='" . $_GET["userName"] . "' and password = '". $_GET["password"]."'";
		$count  = mysqli_num_rows($result);
		print $count;
		mysqli_close($conn);
	}
?>

Download

This PHP code tutorial was published on May 8, 2013.

↑ Back to Top