AMSOL e-Tutor

AMSOL e-Tutor helps you learn web programming better with examples. It also gives sample codes to implement.

PHP AJAX Basic Understanding


AJAX stands for Asynchronous JavaScript and XML

For understanding let us explain the terms first,

In Synchronous communication Between sender and receiver, synchronization is compulsory, In Asynchronous, it does not requires both partners (sender and receiver) to be active.

JavaScript is client side scripting language, which performs functions in response of browser events, it does not has any effect on server side processing.

XML stands for eXtensible Markup Language, much like HTML, it was designed to store and transport data.

In AJAX concept JavaScript waits for an event, prepares an input, sends it to the server, waits for the response which is in XML format and presents output in predefined browser element or performs predefined action using JavaScript. In Simple words AJAX allows you to contact server, fetch data from the server asynchronously, it updates the content of a web page without reloading it.

AJAX can be implemented with any Server side scripting language like PHP, .NET, JSP etc. In any of the web scripting language it has 4 main declarations,

  • 1- Event listener for any HTML element like textbox, select box, button
  • 2- JavaScript function called in action of event described in step 1
  • 3- Server side script to send input and get response
  • 4- An HTML element to display the response, it can be a span, div, input (mostly declared with an id instead of class, to uniquely identify the target element)

Most common example of AJAX implementation is Google Search Box, as soon you start typing your query, it shows you suggestions without reloading the web page.

In this lesson we will learn to implement AJAX using PHP, an example is mentioned below and explained in coming lines

1- ShowCity function is called on text box Event onkeyup, it is called every time you type keyboard, it should be coded in body part of html code.


<form action="">
  <label for="fname">Search City: </label>
  <input type="text" id="city" name="city" onkeyup="showCity(this.value)" >
</form>

2- JavaScript function to handle AJAX call, JavaScript code has to be between script tag let us explain it line by line,


<script>
function showCity(search) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
     document.getElementById("DivAjax").innerHTML = xhttp.responseText; }
  };
  xhttp.open("GET", "city.php?query="+search, true);
  xhttp.send();
}

</script>

Line 1: function declaration mentioning function name and expected parameter to recive, function will save recieved parameter in a variable named as search

Line 2: An instance intialization of The XMLHttpRequest object, it is an JavaScript object, which will be used to exchange data with a web server.

Line 3 & 4: Response listener is initialized before sending the request, to avoid any response doubts it looks for 2 conditions of XMLHttpRequest object, 1 is readyState and 2nd is status of same object.

Line 5: Will display response recieved from server in to a Div declared with id DivAjax

Line 6: function body closed

Line 7: prepares back end request to server with open method of XMLHttpRequest object, it requires 3 parameters, method (GET or POST), Name of script on server with query string, and type of request (true, false)

Setting type of request to true means you are making an asynchronous request. That means the code does not pause until the http request is complete.

A synchronous call locks up the browser so nothing else runs. That can cause problems, so people prefer asynchronous.

Line 8: actually sends back end request to server with send method of XMLHttpRequest object.

Keep in mind Response listener is in wait for response from server mentioned in line 3,4

Response Container: Below mentioned div is the element where response is to be shown.

	<div id="DivAjax">
		Response Div
	</div>
city.php cities are saved in an mysql data table
$conn = mysqli_connect('localhost', 'root', '', 'db1');

if (isset($_GET['search'])){$search = mysqli_real_escape_string($conn, $_GET['search']);}

$RESPONSE = "";
$result = mysqli_query($conn, "SELECT * FROM cities WHERE HEADING LIKE '%$search%' ");
while($row = mysqli_fetch_array($result)){
	$HEADING = $row['HEADING'];
	$RESPONSE .= $HEADING.', ';
	}

echo $RESPONSE;	

 

Download city mysql table