AJAX Live Search in PHP

Hello dear readers! welcome back to another section of our tutorial on PHP. In this tutorial guide, we will be studying about AJAX Live Search in PHP.

AJAX is used in communicating with the web pages and also the web servers.


Below example demonstrates a search field using AJAX -

         span {
            color: green;
         function showHint(str) {
            if (str.length == 0) {
               document.getElementById("txtHint").innerHTML = "";
            }else {
               var xmlhttp = new XMLHttpRequest();
               xmlhttp.onreadystatechange = function() {
                  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                     document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
               xmlhttp.open("GET", "php_ajax.php?q=" + str, true);
      <p><b>Search your favourite tutorials:</b></p>
         <input type = "text" onkeyup = "showHint(this.value)">
      <p>Entered Course name: <span id="txtHint"></span></p>

The above code opens a file, name called as php_ajax.php by using GET method, so we need to create a file, name called as php_ajax php in same directory and output will be attached with txtHint.


It contains arrays of course names and it returns the value to the web browser -

   // Array with names
   $a[] = "Android";
   $a[] = "B programming language";
   $a[] = "C programming language";
   $a[] = "D programming language";
   $a[] = "AJAX";
   $a[] = "JavaScript";
   $a[] = "DOM";
   $a[] = "HTML5";
   $a[] = "jQuery";
   $a[] = "Java";
   $a[] = "K programming language";
   $a[] = "PHP";
   $a[] = "Microsoft technologies";
   $a[] = "Networking";
   $a[] = "Open Source";
   $a[] = "Prototype";
   $a[] = "MySQL";
   $a[] = "Restful web services";
   $a[] = "CSS";
   $a[] = "WordPress";
   $a[] = "Python";
   $a[] = "VB Script";
   $a[] = "Web Technologies";
   $a[] = "Xerox Technology";
   $a[] = "JASON";
   $a[] = "XML";
   $q = $_REQUEST["q"];
   $hint = "";
   if ($q !== "") {
      $q = strtolower($q);
      $len = strlen($q);
      foreach($a as $name) {
         if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
               $hint = $name;
            }else {
               $hint .= ", $name";
   echo $hint === "" ? "Please enter a valid course name" : $hint;


When the above code is executed, it will produce the following result -

Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial guide, we are going to be studying about AJAX XML Parser in PHP.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.