Category: AJAX

  • AJAX RSS Feed Example

    Really Simple Syndication (RSS)

    RSS, which stands for Really Simple Syndication, is used to publish often updated information from website like audio, video, images, etc. We can integrate RSS feeds to a website by using AJAX and PHP. This code demonstrates how to show RSS feeds in our site.

    Index.html

    The index page should be as follows −

    <html><head><script>
    
      function showRSS(str) {
         if (str.length == 0) { 
            document.getElementById("output").innerHTML = "";
            return;
         }
         if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
         } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
               document.getElementById("output").innerHTML = xmlhttp.responseText;
            }
         }
         xmlhttp.open("GET","rss.php?q="+str,true);
         xmlhttp.send();
      }
    </script></head><body><p>Please Select an option to get RSS:</p><form><select onchange = "showRSS(this.value)"><option value = "">Select an RSS-feed:</option><option value = "cnn">CNN</option><option value = "bbc">BBC News</option><option value = "pc">PC World</option></select></form><br><div id = "output">RSS-feeds</div></body></html>

    rss.php

    “rss.php” has contained syntax about how to get access to RSS Feeds RSS Feeds and return RSS Feeds to the webpages.

    <?php
       $q = $_GET["q"];
    
       if($q == "cnn") {
    
      $xml = ("http://rss.cnn.com/rss/cnn_topstories.rss");
    } elseif($q == "bbc") {
      $xml = ("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/americas/rss.xml");
    } elseif($q = "pcw"){
      $xml = ("http://www.pcworld.com/index.rss");
    } $xmlDoc = new DOMDocument(); $xmlDoc->load($xml); $channel = $xmlDoc->getElementsByTagName('channel')->item(0); $channel_title = $channel->getElementsByTagName('title') ->item(0)->childNodes->item(0)->nodeValue; $channel_link = $channel->getElementsByTagName('link') ->item(0)->childNodes->item(0)->nodeValue; $channel_desc = $channel->getElementsByTagName('description') ->item(0)->childNodes->item(0)->nodeValue; echo("<p><a href = '" . $channel_link . "'>" .
      $channel_title . "&lt;/a&gt;");
    echo("<br>"); echo($channel_desc . "</p>"); $x = $xmlDoc->getElementsByTagName('item'); for ($i = 0; $i<=2; $i++) {
      $item_title = $x-&gt;item($i)-&gt;getElementsByTagName('title')
      -&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;
      $item_link = $x-&gt;item($i)-&gt;getElementsByTagName('link')
      -&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;
      $item_desc = $x-&gt;item($i)-&gt;getElementsByTagName('description')
      -&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;
      echo ("&lt;p&gt;&lt;a href = '" . $item_link . "'&gt;" . $item_title . "&lt;/a&gt;");
      echo ("&lt;br&gt;");
      echo ($item_desc . "&lt;/p&gt;");
    } ?>

    It will produce the following output −

    PHP RSS Feed Example
  • AJAX Auto Complete Search

    Autocomplete feature is a typeahead mechanism to show input suggestion as the user enters data in the search box provided. It is also called live search because it reacts to the users’ input. In this example, we shall use AJAX and XML parser in PHP to demonstrate the use of auto complete text box.

    This application has three main constituents −

    • The XML Document
    • JavaScript Code
    • XML Parser in PHP

    Let us now discuss these three constituents in detail −

    The XML Document

    Save the following XML script as “autocomplete.xml” in the document root folder

    <?xml version = "1.0" encoding = "utf-8"?><pages><link><title>android</title><url>https://www.tutorialspoint.com/android/index.htm</url></link><link><title>Java</title><url>https://www.tutorialspoint.com/java/index.htm</url></link><link><title>CSS </title><url>https://www.tutorialspoint.com/css/index.htm</url></link><link><title>angularjs</title><url>https://www.tutorialspoint.com/angularjs/index.htm </url></link><link><title>hadoop</title><url>https://www.tutorialspoint.com/hadoop/index.htm </url></link><link><title>swift</title><url>https://www.tutorialspoint.com/swift/index.htm </url></link><link><title>ruby</title><url>https://www.tutorialspoint.com/ruby/index.htm </url></link><link><title>nodejs</title><url>https://www.tutorialspoint.com/nodejs/index.htm </url></link></pages>

    JavaScript Code

    The following script renders a text field for the user to enter a course name of his choice. On every keystroke a JavaScript function is called, and the input value is passed to the server-side PHP script with GET method. The servers response is asynchronously rendered.

    Save this code as “index.php“.

    <html><head><script>
    
      function showResult(str) {
         if (str.length == 0) {
            document.getElementById("livesearch").innerHTML = "";
            document.getElementById("livesearch").style.border = "0px";
            return;
         }
         if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
         } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
               document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
               document.getElementById("livesearch").style.border = "1px solid #A5ACB2";
            }
         }
         xmlhttp.open("GET","livesearch.php?q="+str,true);
         xmlhttp.send();
      }
    </script></head><body><form><h2>Enter Course Name</h2><input type = "text" size = "30" onkeyup = "showResult(this.value)"><div id = "livesearch"></div><a href = "https://www.tutorialspoint.com">More Details</a></form></body></html>

    XML Parser in PHP

    This the PHP script on the server. It parses the given XML source document, reads the characters entered in the input field, searches for it in the parsed XNL object, and sends back the response.

    Save the following code as “livesearch.php”.

    <?php
       $xml_doc = new DOMDocument();
       $xml_doc->load('autocomplete.xml');
    
       $x=$xml_doc->getElementsByTagName('link');
    
       $q = $_GET['q'];
       $result = '';
       foreach($x as $node) {
    
      if (stripos("{$node-&gt;nodeValue}", $q) !== false) {
         $result .= "{$node-&gt;nodeValue}";
      }
    } // Set $response to "No records found." in case no hint was found // or the values of the matching values if ($result == '')
      $result = 'No records found.';
    // show the results or "No records found." echo $result; ?>

    With the XAMPP server running, visit “http://localhost/index.php” and the browser displays a input text field. For each character typed in it, the relevant suggestions appear below it.

  • AJAX XML Parser

    Using PHP with AJAX, we can parse an XML document from local directory as well as on a server. The following example demonstrates how to parse XML with web browser.

    The client-end script renders a HTML form and defines a JavaScript function for sending a HTTP request to the server with XMLHttpRequest object.

    On the server, a PHP script loads the DOM object from the required XML document, fetches the selected course from $_REQUEST variable, and renders the details of the course chosen as the response back to the client.

    Step 1

    The following XML document is stored on the document root of the XAMPP server.

    <?xml version = "1.0" encoding = "utf-8"?><CATALOG><SUBJECT><COURSE>Android</COURSE><COUNTRY>India</COUNTRY><COMPANY>TutorialsPoint</COMPANY><PRICE>$10</PRICE><YEAR>2015</YEAR></SUBJECT><SUBJECT><COURSE>Html</COURSE><COUNTRY>India</COUNTRY><COMPANY>TutorialsPoint</COMPANY><PRICE>$15</PRICE><YEAR>2015</YEAR></SUBJECT><SUBJECT><COURSE>Java</COURSE><COUNTRY>India</COUNTRY><COMPANY>TutorialsPoint</COMPANY><PRICE>$20</PRICE><YEAR>2015</YEAR></SUBJECT><SUBJECT><COURSE>Microsoft</COURSE><COUNTRY>India</COUNTRY><COMPANY>TutorialsPoint</COMPANY><PRICE>$25</PRICE><YEAR>2015</YEAR></SUBJECT></CATALOG>

    Step 2

    The AJAX code below has a HTML form and a JavaScript function to raise HTTP request through XMLHttpRequest object.

    <html><head><script>
    
      function showCD(str) {
         if (str == "") {
            document.getElementById("txtHint").innerHTML = "";
            return;
         }
         if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
         } else {  
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
               document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
         }
         xmlhttp.open("GET","hello.php?q="+str,true);
         xmlhttp.send();
      }
    </script></head><body><form>
      Select a Course:
      &lt;select name = "cds" onchange = "showCD(this.value)"&gt;&lt;option value = ""&gt;Select a course:&lt;/option&gt;&lt;option value = "Android"&gt;Android &lt;/option&gt;&lt;option value = "Html"&gt;HTML&lt;/option&gt;&lt;option value = "Java"&gt;Java&lt;/option&gt;&lt;option value = "Microsoft"&gt;MS technologies&lt;/option&gt;&lt;/select&gt;&lt;/form&gt;&lt;div id = "txtHint"&gt;&lt;b&gt;Course info will be listed here...&lt;/b&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Step 3

    The server-side PHP script to search within the XML document is as follows −

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

    Visit "http://localhost/example.php" to let the user select a course. Upon selection, the relevant details are fetched from the server and displayed as below −

    PHP AJAX XML Parser
  • AJAX Search

    AJAX is a shortform of the term Asynchronous JavaScript and XML. Ajax is used to build fast and dynamic web pages. Below example demonstrates interaction with the backend PHP script with AJAX functions to provide a search field on the webpage.

    Step 1

    Save the following script as “example.php” −

    <html><head><style>
    
      span {
         color: green;
      }
    </style><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 &amp;&amp; xmlhttp.status == 200) {
                  document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
               }
            }
            xmlhttp.open("GET", "hello.php?q=" + str, true);
            xmlhttp.send();
         }
      }
    </script></head><body><p><b>Search your favourite tutorials:</b></p><form><input type = "text" onkeyup = "showHint(this.value)"></form><p>Entered Course name: <span id="txtHint"></span></p></body></html>

    This code is essentially a HTML script that renders a HTML form with a text field. On its onkeyup event, a showHint() JavaScript function is called. The function sends a HTTP GET request to another PHP script on the server.

    Step 2

    Save the following script as “php_ajax.php” −

    <?php
       // Array with names
       $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";
       $a[] = "Microsoft technologies";
       $a[] = "Networking";
       $a[] = "Open Source";
       $a[] = "Prototype";
       $a[] = "QC";
       $a[] = "Restful web services";
       $a[] = "Scrum";
       $a[] = "Testing";
       $a[] = "UML";
       $a[] = "VB Script";
       $a[] = "Web Technologies";
       $a[] = "Xerox Technology";
       $a[] = "YQL";
       $a[] = "ZOPL";
    
       $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; ?>

    Step 3

    We will start this application by opening example.php in the browser by entering the URL http://localhost/example.php

    On every keystroke in the search field, a GET request goes to the server. The server script reads the character from $_REQUEST array and searches for the course name that matches. The matched value is displayed below the text field in the browser.

  • AJAX Introduction

    PHP powered web applications often make use of AJAX, together they are useful to create dynamic and interactive web applications. AJAX stands for Asynchronous Javascript and XML. It allows webpages to be updated asynchronously without reloading the entire page.

    In AJAX applications, the exchange of data between a web browser and the server-side PHP script is asynchronous. PHP is a server-side scripting language that can be used to generate dynamic content and process data.

    AJAX creates an additional layer known as AJAX engine in between the web application and web server due to which we can make background server calls using JavaScript and retrieve the required data, can update the requested portion of a web page without casing full reload of the page. It reduces the page refresh timing and provides a fast and responsive experience to the user.

    PHP AJAX Introduction

    What is Required to Run AJAX?

    The technologies that are used by AJAX are already implemented in all the Morden browsers. So the client does not require any extra module to run the AJAX application. The technologies used by AJAX are −

    • Javascript − It is an important part of AJAX. It allows you to create client-side functionality. Or we can say that it is used to create AJAX applications.
    • XML − It is used to exchange data between web server and client.
    • The XMLHttpRequest − It is used to perform asynchronous data exchange between a web browser and a web server.
    • HTML and CSS − It is used to provide markup and style to the webpage text.
    • DOM − It is used to interact with and alter the webpage layout and content dynamically.

    To use AJAX with PHP, you will need to use the XMLHttpRequest object in JavaScript to send requests to the PHP server. The PHP server will then process the request and return a response, typically in the form of JSON or XML. The JavaScript code can then parse the response and update the web page accordingly.

    The XMLHttpRequest object in JavaScript is a browser-based API that allows developers to make HTTP requests to a server without reloading the page. This is the foundation of AJAX programming, which allows for dynamic and interactive web applications.

    The XMLHttpRequest object can be used to −

    • Retrieve data from a server, such as JSON, XML, or HTML.
    • Send data to a server, such as form data or file uploads.
    • Update a web page without reloading it.
    • Create chat applications and other interactive features.

    To use the XMLHttpRequest object, you first need to create a new instance of it. Then, you can use the open() method to specify the HTTP method and request URL. Next, you can set any request headers, if needed. Finally, you can send the request using the send() method.

    Example

    Here is a simple JavaScript code of how to use the XMLHttpRequest object to retrieve data from a server −

    // Create a new XMLHttpRequest objectvar xhr =newXMLHttpRequest();// Set the HTTP method and request URL
    xhr.open("GET","test.php");// Send the request
    xhr.send();// Listen for the onload event to be fired
    xhr.onload =function(){// Check the status code to ensure the request was successfulif(xhr.status ===200){// Get the response data.var users =JSON.parse(xhr.responseText);// Do something with the user data.}else{// Handle the error}};

    The PHP script on the server retrieves the data from AJAX request and sends back the response.

    // Get the request data.$name=$_GET["name"];// Create a response object.$response=newstdClass();$response->message="Hello, $name!";// Send the response back to the client.header("Content-Type: application/json");echojson_encode($response);