PHP - AJAX Introduction
AJAX is about updating parts of a web page, without reloading the whole page.
What is AJAX?
AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.
How AJAX Works
AJAX
AJAX is Based on Internet Standards
AJAX is based on internet standards, and uses a combination of:
XMLHttpRequest object (to exchange data asynchronously with a server)
JavaScript/DOM (to display/interact with the information)
CSS (to style the data)
XML (often used as the format for transferring data)
AJAX applications are browser- and platform-independent!
Google Suggest
AJAX was made popular in 2005 by Google, with Google Suggest.
Google Suggest is using AJAX to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.
Start Using AJAX Today
In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP.
PHP - AJAX and PHP
AJAX is used to create more interactive applications.
AJAX PHP Example
The following example will demonstrate how a web page can communicate with a web server while a user type characters in an input field:
Example
Start typing a name in the input field below:
First name:
Suggestions:
Example Explained
In the example above, when a user types a character in the input field, a function called "showHint()" is executed.
The function is triggered by the onkeyup event.
Here is the HTML code:
Example
Firstname
Lastname
Age
Hometown
Job
";
while($row = mysqli_fetch_array($result)) {
echo "";
echo "" . $row['FirstName'] . " ";
echo "" . $row['LastName'] . " ";
echo "" . $row['Age'] . " ";
echo "" . $row['Hometown'] . " ";
echo "" . $row['Job'] . " ";
echo " ";
}
echo "";
mysqli_close($con);
?>
Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:
PHP opens a connection to a MySQL server
The correct person is found
An HTML table is created, filled with data, and sent back to the "txtHint" placeholder
PHP Example - AJAX and XML
AJAX can be used for interactive communication with an XML file.
AJAX XML Example
The following example will demonstrate how a web page can fetch information from an XML file with AJAX:
Example
CD info will be listed here...
Example Explained - The HTML Page
When a user selects a CD in the dropdown list above, a function called "showCD()" is executed. The function is triggered by the "onchange" event:
"); } } ?> When the CD query is sent from the JavaScript to the PHP page, the following happens: PHP creates an XML DOM object Find all elements that matches the name sent from the JavaScript
Output the album information (send to the "txtHint" placeholder)
PHP Example - AJAX Live Search
AJAX can be used to create more user-friendly and interactive searches.
AJAX Live Search
The following example will demonstrate a live search, where you get search results while you type.
Live search has many benefits compared to traditional searching:
Results are shown as you type
Results narrow as you continue typing
If results become too narrow, remove characters to see a broader result
Search for a W3Schools page in the input field below:
The results in the example above are found in an XML file (links.xml). To make this example small and simple, only six results are available.
Example Explained - The HTML Page
When a user types a character in the input field above, the function "showResult()" is executed. The function is triggered by the "onkeyup" event:
Source code explanation:
If the input field is empty (str.length==0), the function clears the content of the livesearch placeholder and exits the function.
If the input field is not empty, the showResult() function executes the following:
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the input field)
The PHP File
The page on the server called by the JavaScript above is a PHP file called "livesearch.php".
The source code in "livesearch.php" searches an XML file for titles matching the search string and returns the result:
load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
//get the q parameter from URL
$q=$_GET["q"];
//lookup all links from the xml file if length of q>0
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) {
//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {
if ($hint=="") {
$hint="" .
$y->item(0)->childNodes->item(0)->nodeValue . "";
} else {
$hint=$hint . "
" . $y->item(0)->childNodes->item(0)->nodeValue . ""; } } } } } // Set output to "no suggestion" if no hint was found // or to the correct values if ($hint=="") { $response="no suggestion"; } else { $response=$hint; } //output the response echo $response; ?> If there is any text sent from the JavaScript (strlen($q) > 0), the following happens: Load an XML file into a new XML DOM object Loop through all elements to find matches from the text sent from the JavaScript
Sets the correct url and title in the "$response" variable. If more than one match is found, all matches are added to the variable
If no matches are found, the $response variable is set to "no suggestion"
PHP Example - AJAX Poll
AJAX Poll
The following example will demonstrate a poll where the result is shown without reloading.
Do you like PHP and AJAX so far?
Yes:
No:
Example Explained - The HTML Page
When a user chooses an option above, a function called "getVote()" is executed. The function is triggered by the "onclick" event:
The getVote() function does the following:
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (vote) is added to the URL (with the value of the yes or no option)
The PHP File
The page on the server called by the JavaScript above is a PHP file called "poll_vote.php":
The value is sent from the JavaScript, and the following happens:
Get the content of the "poll_result.txt" file
Put the content of the file in variables and add one to the selected variable
Write the result to the "poll_result.txt" file
Output a graphical representation of the poll result
The Text File
The text file (poll_result.txt) is where we store the data from the poll.
It is stored like this:
0||0
The first number represents the "Yes" votes, the second number represents the "No" votes.
Note: Remember to allow your web server to edit the text file. Do NOT give everyone access, just the web server (PHP).
Start typing a name in the input field below:
Suggestions:
Code explanation: First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint placeholder and exit the function. However, if the input field is not empty, do the following: Create an XMLHttpRequest object Create the function to be executed when the server response is ready Send the request off to a PHP file (gethint.php) on the server Notice that q parameter is added to the url (gethint.php?q="+str) And the str variable holds the content of the input field The PHP File - "gethint.php" The PHP file checks an array of names, and returns the corresponding name(s) to the browser: PHP - AJAX and MySQL AJAX can be used for interactive communication with a database. AJAX Database Example The following example will demonstrate how a web page can fetch information from a database with AJAX: Example Person info will be listed here... Example Explained - The MySQL Database The database table we use in the example above looks like this: id FirstName LastName Age Hometown Job 1 Peter Griffin 41 Quahog Brewery 2 Lois Griffin 40 Newport Piano Teacher 3 Joseph Swanson 39 Quahog Police Officer 4 Glenn Quagmire 41 Quahog Pilot Example Explained In the example above, when a user selects a person in the dropdown list above, a function called "showUser()" is executed. The function is triggered by the onchange event. Here is the HTML code: ExamplePerson info will be listed here...
Code explanation:
First, check if person is selected. If no person is selected (str == ""), clear the content of txtHint and exit the function. If a person is selected, do the following:
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
The PHP File
The page on the server called by the JavaScript above is a PHP file called "getuser.php".
The source code in "getuser.php" runs a query against a MySQL database, and returns the result in an HTML table:
CD info will be listed here...
The showCD() function does the following:
Check if a CD is selected
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
The PHP File
The page on the server called by the JavaScript above is a PHP file called "getcd.php".
The PHP script loads an XML document, "cd_catalog.xml", runs a query against the XML file, and returns the result as HTML:
load("cd_catalog.xml");
$x=$xmlDoc->getElementsByTagName('ARTIST');
for ($i=0; $i<=$x->length-1; $i++) {
//Process only element nodes
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++) {
//Process only element nodes
if ($cd->item($i)->nodeType==1) {
echo("" . $cd->item($i)->nodeName . ": ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo(""); } } ?> When the CD query is sent from the JavaScript to the PHP page, the following happens: PHP creates an XML DOM object Find all
" . $y->item(0)->childNodes->item(0)->nodeValue . ""; } } } } } // Set output to "no suggestion" if no hint was found // or to the correct values if ($hint=="") { $response="no suggestion"; } else { $response=$hint; } //output the response echo $response; ?> If there is any text sent from the JavaScript (strlen($q) > 0), the following happens: Load an XML file into a new XML DOM object Loop through all
Do you like PHP and AJAX so far?
Result:
Yes: | % |
No: | % |
Comments