PHP – AJAX Search

By | October 1, 2021
PHP - AJAX Search

You can include the AJAX code within the PHP code that allows you to communicate web pages and the webserver. Below example gives you an outlook on how you can use search filed with AJAX and PHP working together. Check more about PHP – AJAX Search below.

PHP – AJAX Search

Below code will open the file (demo_file.php) using the GET method.

Example:

<html>
   <head>
<script>
         function showHint(str) {
            if (str.length == 0) {
               document.getElementById("txtHint").innerHTML = "";
               return;
            }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);
               xmlhttp.send();
            }
         }
      </script>
   </head>
   <body>
<p><b>Search for tutorials:</b></p>
      <form>
         <input type = "text" onkeyup = "showHint(this.value)">
      </form>
      <p>Selected Course name: <span id="txtHint"></span></p>
   </body>
</html>

Output

Search for Tutorials

Vamware

demo_file.php

<?php
   // Array with values
   $a[] = "Android";
   $a[] = "B programming language";
   $a[] = "C programming language";
   $a[] = "D programming language";
   $a[] = "euphoria";
   $a[] = "F#";
   $a[] = "GWT";
   $a[] = "HTML5";
   $a[] = "ibatis";
   $a[] = "Java";
   $a[] = "K programming language";
   $a[] = "Lisp";
$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 correct course name" : $hint;
?>

People are also reading:

Vamware

Leave a Reply

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