Implementing AJAX
We usually implement AJAX whenever we need to insert or fetch data from the server-side database tables, thus improving performance.
Let's say we want to display detailed book information whose ISBN number has been entered by the user. This data is already stored in the books server-side database table.
We'll need two things to fetch the data:
- A function to invoke AJAX method
- A server side PHP script
Invoking the AJAX Method
To implement AJAX, we need to invoke the ajax()
method, and we will do so by creating a function called showdetails
. The user-entered ISBN number is passed to showdetails
as a parameter. The code of showdetails
is shown in Listing 1.
Listing 1. Invoking the ajax() Method
function showdetails(isbn)
{
$.ajax({
type:"POST",
url:"getdetails.php",
data: 'isbn='+isbn,
success:function(html){
$('#bookdetails').append(html);
jQT.goTo('#bookdetailsdisplay',
'slide');
}
});
return
false;
}
The ajax()
method loads a remote page via an HTTP request, and also creates and returns the XMLHttpRequest
object required to talk to the server asynchronously. The ajax()
method takes one argument, an object of key/value pairs, which is used to initialize and handle the request. The ajax()
method syntax is:
.ajax( object of key/value pairs )
A brief description of key/value pairs frequently used in the ajax()
method are shown in Table 1.
Table 1. Key Value Pairs Used in the ajax() Method
Key | Description |
Type | A string that defines the HTTP method we used for the request—GET or POST . The default is GET . |
url | A string containing the URL of the server script file to which we want to send the request. |
Data | A map or string we want sent to the server script along with the request. The script will then process the sent data.
To create the data map, we retrieve the user-entered information and assign it to variables in the following format:
data:'variable1=value1&variable2=value2.....';
Here's a snippet of how the data map is used:
var cat=$('.category').val();
var subcat=$('.subcategory').val();
data: 'category='+cat+'&subcategory='+subcat,
We assume the Form on our web page contains two input fields, category and subcategory . The information entered into the two fields is retrieved and stored in variables cat and subcat respectively. Thereafter, the data map is created by using these two variables.
We can also assign all the variable=value pairs to a variable and then use it to make our data map, as shown below:
var data='category='+cat+'&subcategory='+subcat;
data: data,
If this data variable exists, it is sent to the server to be assigned to the specified script file, which performs its function and generates a response. We can skip the data variable if we don't want any information passed to the script.
|
success | A callback function executed if the request sent to the script succeeds. The returned response from the server script is assigned to this callback function's parameter. |
The steps involved in Listing 1 are as follows:
- The code in the
showdetails
function invokes the request via the ajax()
method. - In
ajax()
, we specify that the request method we will use is POST
and the name of the server-side script file that will be executed is getdetails.php. - <![endif]>We create a data
string
to be passed to the PHP script consisting of an isbn
variable set to the value of the isbn
passed to the function. - The
data string
, in turn, passes the isbn
number to the script file, getdetails.php. - This script fetches the corresponding ISBN information from the
books
table and generates the appropriate output. The success
call back function will execute if the request passed to the script succeeds. The output of the script will be assigned to the callback function's html
parameter. - The contents of the
html
parameter is then appended to the bookdetails div
element for displaying result. We assume that there exists a div
of id bookdetails
nested inside the div
of id bookdetailsdisplay
. - The statement,
jQT.goTo('#bookdetailsdisplay', 'slide');
navigates to the bookdetailsdisplay
panel with a slide animation to display the response generated by the getdetails.php script. - Finally, we return a value of
false
to the showdetails
function to suppress the default browser click behavior. We explain this code in more detail below.
Let's assume that showdetails
is invoked by a click event on the button created here:
<a class="whiteButton" href="#"
onclick="showdetails('11111-1111-1111');"> Show
Details</a>
A button, called Show Details, is created by assigning a whiteButton
to the hyperlink. When clicked, this button invokes the showdetails
function with a parameter '11111-1111-1111' that has been passed to it. We want to suppress the default browser click behavior, so, we return false
from the showdetails
function.
The Server side PHP Script
The server-side PHP script is the core of the fetch process. The script file getdetails.php reads the isbn
number passed to it via data
and will use this value to fetch the detailed book information from the books
table. The script will generate the output for display in the panel. The code of getdetails.php is shown in listing 2.
Listing 2. getdetails.php
<?php
$isbn =trim($_REQUEST['isbn']);
$connect=mysql_connect("localhost","root", "mce") or die ("Please check your server
connection");
mysql_select_db("shopping");
$query="Select isbn, title, author1, author2, author3, publisher,
publish_date_edition, price, image, description from books where isbn ='$isbn'";
$results =mysql_query($query) or die (mysql_query());
while ($row=mysql_fetch_array($results))
{
extract ($row);
echo '<fieldset style="background-color:white; color:black;">';
echo '<img src=' . $image .'>';
echo '<h3>' . $title . ' by </h3>';
echo '<h4>' . $author1 . '</h4>';
if($author2 !='NULL')
echo '<h4>' . $author2 . '</h4>';
if($author3 !='NULL')
echo '<h4>' . $author3 . '</h4>';
echo '<label>Publisher :</label><h4>' . $publisher . '</h4>';
echo '<h4>' . $publish_date_edition . '</h4>';
echo '<label>Price: </label>';
echo '<em>' . $price . '</em><br/>';
echo '<label>Book Details :</label><h4>' . $description . '</h4>';
echo '</fieldset>';
}
?>
We can see that the above code of the script does the following:
- Retrieves the value of
isbn
from the $_POST
array and stores it in variable $isbn
. - Establishes a connection to the MySQL server using
root
as the user and mce
as the password. - Selects the shopping database to make it active.
- Writes a query to fetch the information for the book having the supplied ISBN number.
- Executes the query and receives the result in a
$result array
. - Retrieves a row from
$result
and stores it into a $row
variable. - Extracts the
$row
containing the retrieved row fields. - Displays the information in the
$row
's fields in a fieldset.
Remember that the detailed information displayed by this PHP script will be returned to the success callback function's html
parameter (see Listing 1). The detailed book information assigned to the html
parameter is then appended to the bookdetails div
element for display.
For more information, refer to my book: "Beginning Web Development for Smartphones: Developing Web Applications with PHP, MySQL and jQTouch" available at Amazon.
History
- 24th September, 2010: Initial version