AMSOL e-Tutor

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

PHP AJAX: Get content/Suggestions as you type like Google Search


We assume you have basic understanding of AJAX, you can learn the basics in the tutorial PHP AJAX Basic Understanding

In this lesson we will learn to implement suggestions show like Google Search, you can implement this idea in any of your project, where products needs to be searched or employees from database.

1st step is to create an text box for input, on its onkeyup event we will call JavaScript function showCity proving types string as value.

	<input name="City" type="text" class="form-control" onkeyup="showCity(this.value)" />

showCity prepares an AJAX request to given PHP script AJX_City.php with an id as query string, it will wait for response and show it in given div container DivCity.


	<script>
//************ GET CITY  ************
function showCity(ID) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
     document.getElementById("DivCity").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "AJX_City.php?id="+ID, true);
  xhttp.send();
}
  
  </script>
  

To understand above script line by line, please read the tutorial PHP AJAX Basic Understanding

AJX_City.php will recieve query string and process the request via mysql and prepares a HTML response and send it back to requesting script.


$conn = mysqli_connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()) {echo "Failed to connect to MySQL: " . mysqli_connect_error();}

$RID=$_GET["id"];

echo '     <table id="example" class="table table-bordered table-striped">
	<thead>
	<tr>
		<th>Sr</th>
		<th>City</th>
	</tr>
	</thead>
	<tbody>';
	
	$A = 1;
	$result = mysqli_query($conn, "SELECT * FROM cities WHERE HEADING LIKE '%$RID%' ORDER BY HEADING");
	while($row = mysqli_fetch_array($result))	{
	$useridX = $row['ID'];
	$HEADING = $row['HEADING'];
	
	
	echo '<tr>
	<td>'.$A.'</td>
	<td>'.$HEADING.'</td>
	</tr>';
	
	$A++;
		}
       
echo '</tbody>
	</table>';	   

Glad to hear you have learned the concept of get contents on the go , you can download example code here