PHP AJAX


December 21, 2021, Learn eTutorial
1307

In this PHP tutorial you will learn all about the AJAX in PHP. We will discuss in detail about the types of AJAX, PHP AJAX connection, rendering pages using AJAX, and so on.

What is AJAX?

AJAX is an abbreviation for Asynchronous JavaScript and XML. AJAX is a new technique for developing better, quicker, and more interactive online applications using XML, HTML, CSS, and Javascript. Synchronous requests are used by traditional web applications to send and receive data from the server. This implies that you fill out a form, press submit, and are sent to a new page with updated information from the server. When you touch the submit button in AJAX, JavaScript will send a request to the server, analyse results, and update the current screen. In its purest form, the user would have no idea that anything was being transferred to the server.

How to use AJAX in PHP?

To illustrate the PHP with AJAX we are creating a script that has the predefined name and we are trying to show the suggestions from the specified name on entering in the field without reloading the current page.

file “Index.html”


 <html>
 <head>
  <script>
   function showSuggestion(str) {
    if (str.length == 0) {
     document.getElementById('txt')[removed] = '';
     return;
    } else {      var xmlhttp = new XMLHttpRequest(); xmlhttp. ()  {
      if (this.readyState == 4 && this.status == 200) {
       document.getElementById('txt')[removed] = this.responseText;
      }
     };
     xmlhttp.open('GET', 'getnames.php?q=' + str, true);
     xmlhttp.send();
    }
   }
  </script>
 </head>
 <body>   <p><b>Enter the name in the input field below:</b></p>   <form acti >
   <label for="fname">First name:</label>
   <input
    type="text"
    id="fname"
    name="fname"          
   />
  </form>
  <p>Suggestions: <span id="txt"></span></p>
 </body>
</html>

“getname.php”


<?php
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";
$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 === "" ? "no suggestion" : $hint;
?>

Output:


PHP - session

In the above example we can see that the suggestion is occurring without reloading the current web page and it is done with the help of AJAX. We have defined some names in an array and in the AJAX script we are comparing the inputted characters with the characters in the array.

How to use AJAX with XML in PHP?

The AJAX is capable to intact with the XML files. We can demonstrate the interaction of AJAX and XML with example.

Example: file “index.html”


<html>
 <head>
  <script>
   function showCD(str) {
    if (str == '') {
     document.getElementById('txtHint')[removed] = '';
     return;
    }
    if (window.XMLHttpRequest) {
     xmlhttp = new XMLHttpRequest();
    } else {
     xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
    }     xmlhttp. () {
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      document.getElementById('txtHint')[removed] = xmlhttp.responseText;
     }
    };
    xmlhttp.open('GET', 'getcourse.php?q=' + str, true);
    xmlhttp.send();
   }
  </script>
 </head>
 <body>
  <form>
Select a Course:    <select name="cds" >
    <option value="">Select a course:</option>
    <option value="Python">Python</option>
    <option value="PHP">PHP</option>
    <option value="JavaScript">JavaScript</option>
    <option value="GO">GO</option>
   </select>
  </form>
  <div id="txtHint"><b>Course info will be listed here...</b></div>
 </body>
</html>

File “getcourse.php”


<?php
   $q = $_GET["q"];
   $xmlDoc = new DOMDocument();
   $xmlDoc->load("catalog.xml");
   $x = $xmlDoc->getElementsByTagName('COURSE');
   for ($i = 0; $i<=$x->length-1; $i++) {
      if ($x->item($i)->nodeType == 1) {
         if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
            $y = ($x->item($i)->parentNode);
         }
      }
   }
   $cd = ($y->childNodes);
   for ($i = 0;$i<$cd->length;$i++) {
      if ($cd->item($i)->nodeType == 1) {
         echo("" . $cd->item($i)->nodeName . ": ");
         echo($cd->item($i)->childNodes->item(0)->nodeValue);
         echo("
");
      }
   }

File “catalog.xml”


<CATALOG>
   <SUBJECT>
      <COURSE>Python</COURSE>
      <COUNTRY>India</COUNTRY>
      <COMPANY>learnetutorials.com</COMPANY>
   </SUBJECT>
   
   <SUBJECT>
      <COURSE>PHP</COURSE>
      <COUNTRY>India</COUNTRY>
      <COMPANY>learnetutorials.com</COMPANY>
   </SUBJECT>
   
   <SUBJECT>
      <COURSE>JavaScript</COURSE>
      <COUNTRY>India</COUNTRY>
      <COMPANY>learnetutorials.com</COMPANY>
   </SUBJECT>
   
   <SUBJECT>
      <COURSE>GO</COURSE>
      <COUNTRY>India</COUNTRY>
      <COMPANY>learnetutorials.com</COMPANY>
   </SUBJECT>
</CATALOG>

Output:


PHP - session

PHP - session