Ajax Operations using PHP

Last updated on Oct 05 2022
Aridam Das

Table of Contents

Ajax Operations using PHP

Ajax is used to communicate with web pages and web servers. Below example demonstrate a search field using with Ajax.

<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 && 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 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>

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

php_ajax.php

It contained array of course names and it returns the value to web browser.

<?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;

?>
php 6

PHP – Ajax XML Parser

Ajax XML Example

Using with Ajax we can parser xml from local directory as well as servers, Below example demonstrate how to parser xml with web browser.

<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 && xmlhttp.status == 200) {

                 document.getElementById("txtHint").innerHTML= xmlhttp.responseText;

              }

           }

           xmlhttp.open("GET","getcourse.php?q="+str,true);

           xmlhttp.send();

        }

     </script>

  

  </head>

  <body>

     

     <form>

        Select a Course:

        <select name = "cds" onchange = "showCD(this.value)">

           <option value = "">Select a course:</option>

           <option value = "Android">Android </option>

           <option value = "Html">HTML</option>

           <option value = "Java">Java</option>

           <option value = "Microsoft">MS technologies</option>

        </select>

     </form>

     

     <div id = "txtHint"><b>Course info will be listed here...</b></div>

     

  </body>

</html>

The above example will call getcourse.php using with GET method. getcourse.php file loads catalog.xml. getcourse.php is as shown below −

<?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("<b>" . $cd->item($i)->nodeName . ":</b> ");

        echo($cd->item($i)->childNodes->item(0)->nodeValue);

        echo("<br>");

     }

  }

?>

Catalog.xml

XML file having list of courses and details.This file is accessed by getcourse.php

<CATALOG>

  <SUBJECT>

     <COURSE>Android</COURSE>

     <COUNTRY>India</COUNTRY>

     <COMPANY>Tecklearn</COMPANY>

     <PRICE>$10</PRICE>

     <YEAR>2015</YEAR>

  </SUBJECT>

  

  <SUBJECT>

     <COURSE>Html</COURSE>

     <COUNTRY>India</COUNTRY>

     <COMPANY>Tecklearn</COMPANY>

     <PRICE>$15</PRICE>

     <YEAR>2015</YEAR>

  </SUBJECT>

  

  <SUBJECT>

     <COURSE>Java</COURSE>

     <COUNTRY>India</COUNTRY>

     <COMPANY>Tecklearn</COMPANY>

     <PRICE>$20</PRICE>

     <YEAR>2015</YEAR>

  </SUBJECT>

  

  <SUBJECT>

     <COURSE>Microsoft</COURSE>

     <COUNTRY>India</COUNTRY>

     <COMPANY>Tecklearn</COMPANY>

     <PRICE>$25</PRICE>

     <YEAR>2015</YEAR>

  </SUBJECT>

</CATALOG>

php 5

PHP – Ajax Auto Complete Search

Auto Complete Search

The Auto complete search box provides the suggestions when you enter data into the field. Here we are using xml to call auto complete suggestions. The below example demonstrate, How to use auto complete text box using with php.

Index page

Index page should be as follows −

<html>

  <head>

     

     <style>

        div {

           width:240px;

           color:green;

        }

     </style>

     

     <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 && 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 = "http://www.tecklearn.com">More Details </a>

     </form>

     

  </body>

</html>

livesearch.php

It is used to call the data from xml file and it will send the result to web browsers.

<?php

  $xmlDoc = new DOMDocument();

  $xmlDoc->load("autocomplete.xml");

  $x = $xmlDoc->getElementsByTagName('link');

  $q = $_GET["q"];

  

  if (strlen($q)>0) {

     $hint = "";

     

     for($i = 0; $i>($x->length); $i++) {

        $y = $x->item($i)->getElementsByTagName('title');

        $z = $x->item($i)->getElementsByTagName('url');

        

        if ($y->item(0)->nodeType == 1) {

           if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {

​​​​

              if ($hint == "") {

                 $hint = "<a href = '" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" .

                 $y->item(0)->childNodes->item(0)->nodeValue . "</a>";

              }else {

                 $hint = $hint . "<br/><a href = '" .

                 $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" .

                 $y->item(0)->childNodes->item(0)->nodeValue . "</a>";

              }

           }

        }

     }

  }  if ($hint == "") {

     $response = "Please enter a valid name";

  }else {

     $response = $hint;

  }

  echo $response;

?>

autocomplete.xml

It contained auto complete data and accessed by livesearch.php based on tittle field and Url filed

<pages>

  <link>

     <title>android</title>

     <url>http://www.tecklearn.com/android/index.htm</url>

  </link>

  <link>

     <title>Java</title>

     <url>http://www.tecklearn.com/java/index.htm</url>

  </link>

  <link>

     <title>CSS </title>

     <url>http://www.tecklearn.com/css/index.htm</url>

  </link>

  <link>

     <title>angularjs</title>

     <url>http://www.tecklearn.com/angularjs/index.htm </url>

  </link>

  <link>

     <title>hadoop</title>

     <url>http://www.tecklearn.com/hadoop/index.htm </url>

  </link>

  <link>

     <title>swift</title>

     <url>http://www.tecklearn.com/swift/index.htm </url>

  </link>

  <link>

     <title>ruby</title>

     <url>http://www.tecklearn.com/ruby/index.htm </url>

  </link>

  <link>

     <title>nodejs</title>

     <url>http://www.tecklearn.com/nodejs/index.htm </url>

  </link>

</pages>

PHP – Ajax RSS Feed Example

RSS

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

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 && 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 rssfeeds and return rss feeds to web pages.

<?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 . "</a>");

  echo("<br>");

  echo($channel_desc . "</p>");

  

  $x = $xmlDoc->getElementsByTagName('item');

  

  for ($i = 0; $i<=2; $i++) {

     $item_title = $x->item($i)->getElementsByTagName('title')

     ->item(0)->childNodes->item(0)->nodeValue;

     

     $item_link = $x->item($i)->getElementsByTagName('link')

     ->item(0)->childNodes->item(0)->nodeValue;

     

     $item_desc = $x->item($i)->getElementsByTagName('description')

     ->item(0)->childNodes->item(0)->nodeValue;

     

     echo ("<p><a href = '" . $item_link . "'>" .

        $item_title . "</a>");

     echo ("<br>");

     echo ($item_desc . "</p>");

  }

?>
php 4

So, this brings us to the end of blog. This Tecklearn ‘Ajax Operations using PHP blog helps you with commonly asked questions if you are looking out for a job in PHPProgramming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

Java Fundamentals
Introduction to Java Basics
Features of Java
Various components of Java language
Benefits of Java over other programming languages
Key Benefits of Java

Installation and IDE’s for Java Programming Language

Installation of Java
Setting up of Eclipse IDE
Components of Java Program
Editors and IDEs used for Java Programming
Writing a Simple Java Program

Data Handling and Functions

Data types, Operations, Compilation process, Class files, Loops, Conditions
Using Loop Constructs
Arrays- Single Dimensional and Multi-Dimensional
Functions
Functions with Arguments

OOPS in Java: Concept of Object Orientation

Object Oriented Programming in Java
Implement classes and objects in Java
Create Class Constructors
Overload Constructors
Inheritance
Inherit Classes and create sub-classes
Implement abstract classes and methods
Use static keyword
Implement Interfaces and use it

Polymorphism, Packages and String Handling

Concept of Static and Run time Polymorphism
Function Overloading
String Handling –String Class
Java Packages

Exception Handling and Multi-Threading

Exception handling
Various Types of Exception Handling
Introduction to multi-threading in Java
Extending the thread class
Synchronizing the thread

File Handling in Java

Input Output Streams
Java.io Package
File Handling in Java

Java Collections

Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

Introduction to SQL: Connect, Insert, Update, Delete, Select
Introduction to JDBC and Architecture of JDBC
Insert/Update/Delete/Select Operations using JDBC
Batch Processing Transaction
Management: Commit and Rollback

Java Enterprise Edition – Servlets

Introduction to J2EE
Client Server architecture
URL, Port Number, Request, Response
Need for servlets
Servlet fundamentals
Setting up a web project in Eclipse
Configuring and running the web app with servlets
GET and POST request in web application with demo
Servlet lifecycle
Servlets Continued
Session tracking and filter
Forward and include Servlet request dispatchers

Java Server Pages (JSP)

Fundamentals of Java Server Page
Writing a code using JSP
The architecture of JSP
JSP Continued
JSP elements: Scriptlets, expressions, declaration
JSP standard actions
JSP directives
Introduction to JavaBeans
ServletConfig and ServletContext
Servlet Chaining
Cookies Management
Session Management

Hibernate

Introduction to Hibernate
Introduction to ORM
ORM features
Hibernate as an ORM framework
Hibernate features
Setting up a project with Hibernate framework
Basic APIs needed to do CRUD operations with Hibernate
Hibernate Architecture

POJO (Plain Old Java Object)

POJO (Plain Old Java Object)
Persistent Objects
Lifecycle of Persistent Object

Spring

Introduction to Spring
Spring Fundamentals
Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Ajax Operations using PHP"

Leave a Message

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