If you're like most PHP developers, you probably learned your craft the old-fashioned way. You learned how to define and build simple PHP pages, connect them to simple MySQL tables, and off you went. As you progressed through various skill levels, you learned how to create ever-more complex PHP functionality, and you learned how to join tables in MySQL and perform other advanced tasks.
Along the way, you probably picked up a number of client-side skills to bring your Web applications to life. You may have learned a bit about XHTML or CSS, maybe some JavaScript programming. Depending on the kinds of projects you're used to, you may even have had the chance to work with Ajax to give your Web applications that Web 2.0, or "desktop," feel. If your first experience with Ajax was anything like mine, however, you probably did too much work — hand-rolling your functions and struggling through the process of creating an Ajax-driven page.
For some, Ajax is still a mystery. It's something that the "cool kids" and "bad boys" of Web development/interactivity do, and they've never had the time, patience, or skill to take it on. It's a shame, too, because a lot of clients really like adding Ajax-style functionality — it makes Web applications easier to work with. If you're one of these PHP developers, never fear: By the time you're done reading this article, you'll know enough to become a real Ajax pro.
This article shows how to use jQuery to easily add Ajax functionality to any PHP Web application. You'll build a simple Web application with PHP and MySQL — a phone book containing names and phone numbers. The application has all the standard things you'd expect — a way to search for names or phone numbers, a MySQL table, etc. Next, you'll add jQuery to the application, giving you the ability to search for names and phone numbers in real time, as you type. When you're done, you should have a pretty good grounding in not only some jQuery basics but also in the fundamentals of Ajax.
The best way to describe Ajax is to compare it to what you already know. Most Web pages and applications work in synchronous mode. You click a link or a form's Submit button, and the request is sent to the server, which then processes that request and sends back a response. The best way to sum up this model is "click, wait, view." It's a never-ending rinse-and-repeat cycle that you know all too well. In other words, if your page needed to show constantly updated information, you either had to put in some kind of auto-refresh hack or make the user refresh or click a link to make things happen.
Ajax changes all that. The first A in Ajax stands for asynchronous. Ajax allows you to create a page in any programming language, then refresh different parts of that page with information from a database or some other back-end server process. For example, say you have an e-commerce site that shows products for sale. On each product page, there are the usual items: headlines, sales copy, thumbnail photos, the number of items in stock.
Say you wanted to keep the site visitor updated on how many items were in stock. You could add an Ajax function that would run a separate PHP page containing a MySQL query, then repopulate the information on the original page without any input from the user or without regard to the synchronous nature of the click-wait-view pattern of events.
The j in Ajax stands for JavaScript, and that's what powers all the behavior you get. That's a blessing and a curse, really — a blessing because it's all client-side code, so it's portable and doesn't affect the server; a curse for a lot of PHP developers because it's a different environment than they're used to. That's where tools and frameworks like jQuery come in: They vastly simplify how you interact with Ajax, speeding our time to code completion.
What about the final two pieces: the + and the x? They stand for and XML,
although the XML part is sometimes not really true. Plenty of Ajax applications work
well without any XML code at all: They merely pass HTML or even plain
text back and forth. It's probably more accurate to have the x stand for
XMLHttpRequest, as you're using that object to retrieve
data in the background, thereby not interfering with the display or behavior of the
existing page.
jQuery is a lightweight JavaScript library created by John Resig and released to the Internet in early 2006. It's free and open source software dual-licensed under the Massachusetts Institute of Technology (MIT) and GNU General Public License. It has won over many fans in the development world because it is so simple and straightforward.
Why is it so popular? Because it offers an easy-to-use library that simplifies JavaScript so anyone (yes, even a dyed-in-the-wool back-end programmer) can create marvelous effects without any back-breaking work. You can make Document Object Model (DOM) element selections, modify and manipulate CSS, animate elements, and work with Ajax. All this functionality is available through a single JavaScript file you can download from the jQuery site (see Resources).
After you've downloaded jQuery, you can add it to any HTML or PHP file by including a simple <script> tag:
<script type="text/javascript" src="/path/to/jquery.js"></script> |
Say you had a fairly simple but annoying task to complete — something
intensely manual, such as adding a colon (:) at the
end of every form label on your site. You could go through and hunt for
each form label and add a colon at the end of each line, or you could deploy
the following jQuery code:
Listing 1. Adding a colon using jQuery
<script type="text/javascript">
$(document).ready(function(){
$("label").append(":");
});
</script>
|
This function is simple: It waits until the page is ready and fully loaded (that's the
$(document).ready() part), runs an anonymous
function that finds all DOM label elements, then
appends a colon to the end of the text it finds. The $()
function allows you to access DOM elements with their native names, making this
interface an ideal choice for those developers already familiar with the DOM.
Of course, there are plenty of other things you can do with jQuery, but this is a good
first glance. With a simple built-in function, jQuery ensures that your code will
work because it waits for the page to load. With another single line of code, you
make sweeping changes to all the DOM label elements
the code finds, all in the client, without having to tediously go through all your
markup and make changes there.
Create a simple application: A phone book
Now that the basics of jQuery are out of the way, let's build a simple phone-book application with PHP and MySQL. This application consists of three pieces:
- A MySQL table that will hold your people and phone numbers
- An index.php file with a search form
- A find.php page that queries the database table
You build each element one at a time.
Creating the database table in MySQL is perhaps the easiest part. What you
want for this application is a table that contains the bare minimum of
information — for example, an ID (the table's key), a name field, and
a phone number field. The last two fields can be alphanumeric, so you'll use
the varchar() function. You'll create the ID field as an
autoincrement primary key. Call this table directory
and use the following Structured Query Language (SQL) code to create it:
Listing 2. Use SQL to create directory table
CREATE TABLE `directory` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR( 64 ) NOT NULL , `phone` VARCHAR( 16 ) NOT NULL , PRIMARY KEY ( `id` ) ) TYPE = MYISAM ; |
As you can see, there's nothing complex here. In fact, later on, you'll have plenty of chances to update this application on your own. One way to extend this application is to add a keyword or location field, for example, either of which would allow you to further refine searches. For now, though, let's work with what we have.
Now that you've created the table, you need to populate it. You can use phpMyAdmin or the command line to enter a names and phone numbers. You can also use the following SQL instruction set:
Listing 3. Use SQL to populate the table
insert into `directory` (name,phone) values ('Tom Smith', '512-555-0111');
insert into `directory` (name,phone) values ('Bill Smith', '512-555-0112');
insert into `directory` (name,phone) values ('John Smith', '512-555-0113');
insert into `directory` (name,phone) values ('Jane Smith', '512-555-0114');
insert into `directory` (name,phone) values ('Sara Smith', '512-555-0115');
|
When you're done inputting these values, make sure you get back a list of
records if you run a select * from directory
operation from the command line or click Browse in phpMyAdmin.
Next, you create a simple home page for your application. This page is a PHP file called index.php, but it mostly contains HTML code at this point. When you're done with the find.php file (the next step), you'll circle back around and finish this piece.
For the moment, all you need is a bare-bones HTML file that contains a form. Each element in the form contains a unique ID because you want to be able to identify each piece using jQuery.
Listing 4. HTML file with form
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Search our Phone Directory</h1>
<form id="searchform" method="post">
<div>
<label for="search_term">Search name/phone</label>
<input type="text" name="search_term" id="search_term" />
<input type="submit" value="search" id="search_button" />
</div>
</form>
<div id="search_results"></div>
</body>
</html>
|
Two things should jump out at you right away. First, no action is associated with the
form. That's OK: Remember, this form isn't going to follow the traditional
synchronous pattern of "click, wait, view." Instead, you'll be adding functionality
that will watch user activity in the search_term field.
The second thing you should notice is the search_results
DOM element — the empty one right underneath the form. That's
the DOM element that will contain any responses you get from your search.
Before digging any further into that, however, create your find.php page.
The find.php file is where all your action occurs. It's where the application connects to the database and runs the query against the directory table.
The first part of the find.php file contains your connection information. For purposes of this article, I've embedded that information in the file. For most of you, this information will be in an included or required file or be part of a much larger framework.
Listing 5. Create the find.php file
<?php
define(HOST, "your.host.here");
define(USER, "your-user-name");
define(PW, "your-password");
define(DB, "your-db-name");
$connect = mysql_connect(HOST,USER,PW)
or die('Could not connect to mysql server.' );
mysql_select_db(DB, $connect)
or die('Could not select database.');
|
Next, you'll be getting a search term from the form in the index.php file. Take that
incoming search term and do some simple processing on it before you insert
that value into your database. I'm choosing to use the
strip_tags() and substr()
functions to remove all HTML tags from the search term and to cut it down to size.
This kind of preprocessing is a good idea — you can never really trust user input
100 percent.
In fact, when you have a clean search term, take the extra step of running it through
mysql_escape_string(), which further removes any
other gotchas (such as single quotation marks) that might screw up your database.
$term = strip_tags(substr($_POST['search_term'],0, 100)); $term = mysql_escape_string($term); |
Now build your SQL statement. You want to retrieve any names and
phone numbers from the directory table that match your search term. You'll
make it so that your search term is matched against both the name and phone
fields using LIKE, then run the query using
mysql_query().
Listing 6. Build your SQL statement
$sql = "select name,phone from directory where name like '%$term%' or phone like '%$term%' order by name asc"; $result = mysql_query($sql); |
After you run the query, you can print the results. Initialize a
$string variable to hold your results, then use
mysql_num_rows() to check whether you get any
rows back. If you don't get results for the search term, set
$string to equal "No matches!" If you do get results,
print each name and phone number in the result set. At the end of the process, print the entire string using the echo command:
Listing 7. Print string using
echo command
$string = '';
if (mysql_num_rows($result) > 0){
while($row = mysql_fetch_object($result)){
$string .= "<b>".$row->name."</b> - ";
$string .= $row->phone."</a>";
$string .= "<br/>\n";
}
}else{
$string = "No matches!";
}
echo $string;
?>
|
Of course, this bit of PHP functionality is fairly useful in itself, but right now, there's nothing pointing to it. You need to be able to feed this script a search term. In the next section, you do just that.
At this point, all you have is a pair of innocuous PHP pages and a simple MySQL table. When you add jQuery, this mild-mannered application will be transformed into a modern, Ajax-powered application that will act more like a desktop search application like Spotlight on Mac OS X or Google Desktop Search.
For now, open your index.php file and make sure to add the call to your freshly downloaded jquery.js file.
<script src="./jquery.js"></script> |
Next, create a simple function that prevents your search form from acting like
a typical form. (You'll use the preventDefault()
function to do that.) Reroute all Submit buttons and key-up events (that is,
an event that occurs whenever you type a character on your keyboard) to
a new function you're going to create called ajax_search().
Listing 8. Create function to prevent search form from acting typical
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#search_button").click(function(e){
e.preventDefault();
ajax_search();
});
$("#search_term").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
|
Notice how you're using the slideUp() function to
temporarily hide the search_results DOM
element? And that you used the $() function to
refer to that DOM element by name? If you're at all familiar with CSS, then jQuery's approach is intuitive and familiar. For example, you have a DOM element with a unique ID of search_results, so you use $("#search_results") to refer to it. Simple as that.
Also notice that anytime anyone clicks Search or types a character in
the search_term field, an anonymous function in
each case prevents the default behavior from occurring and reroutes
application flow to the ajax_search() function,
which you'll write next.
The ajax_search() function is fairly simple. You want
to show the DOM element search_results (you'd
previously hidden it, remember), capture the value of the
search_term input field, pass that value to
a function ($.post()) that runs the find.php file
asynchronously, then wait for a response. When the response arrives (and
remember, you made sure that find.php would return some kind of response,
even in the case of zero matches), jQuery fills the search_results
DOM element with that response.
Listing 9.
ajax_search() function
function ajax_search(){
$("#search_results").show();
var search_val=$("#search_term").val();
$.post("./find.php", {search_term : search_val}, function(data){
if (data.length>0){
$("#search_results").html(data);
}
})
}
</script>
|
Now that all systems are in place, you can type a request and see the search
engine work in real time, pulling in records with each key-up event. It also
works when you click Submit. For example, in Figure 1,
having typed the letter a in the search field, the
application returns records for both Jane and Sara Smith, as both names contain
that letter.
Figure 1. Ajax-driven search in action
A lot more work can be done on this application, of course. For example, you could add a keyword field, then allow searches by keyword. Or, you could make it such that each person's records contained tags or keywords for their different areas of expertise. Then, you'd have a resource lookup to find people who could help you with different projects. You could add an e-mail field, a birthday field — whatever — then expand the search parameters.
The point is, the jQuery portion of this application doesn't care what happens on the back end. All it knows is that its passing a search term to a file called find.php. The find.php file doesn't know or care that its receiving its instructions from a jQuery function. As far as it's concerned, the search term comes from an ordinary form submit process, and it uses that data to complete a query, then return the records that match that term.
Learn
-
Check out Learning jQuery, from the author of Learning jQuery and the jQuery Reference Guide.
-
See Alex Walker's "jQuery: Easy JavaScript for Designers" for some easy jQuery tutorials.
-
Nathan Smith's "jQuery Crash Course" (Digital Web Magazine, October 2007) gives you a more in-depth look at the CSS-style element notation of jQuery.
-
jQuery in Action (Bear Bibeault, Yehuda Katz, John Resig, Manning, 2008) is a concise book that guides you through the details of jQuery development.
-
PHP.net is the central resource for PHP developers.
-
Check out the "Recommended PHP reading list."
-
Browse all the PHP content on developerWorks.
-
Follow developerWorks on Twitter.
-
Expand your PHP skills by checking out IBM developerWorks' PHP project resources.
-
To listen to interesting interviews and discussions for software developers, check out developerWorks podcasts.
-
Using a database with PHP? Check out the Zend Core for
IBM, a seamless, out-of-the-box, easy-to-install PHP development and production environment that supports IBM DB2 V9.
-
Stay current with developerWorks' Technical events and webcasts.
-
Check out upcoming conferences, trade shows, webcasts, and other Events around the world that are of interest to IBM open source developers.
-
Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products.
-
Watch and learn about IBM and open source technologies and product functions with the no-cost developerWorks On demand demos.
Get products and technologies
-
Innovate your next open source development project with IBM trial software, available for download or on DVD.
-
Download IBM product evaluation versions, and get your hands on application development tools and middleware products from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®.
Discuss
-
Participate in developerWorks blogs and get involved in the developerWorks community.
-
Participate in the developerWorks PHP Forum: Developing PHP applications with IBM Information Management products (DB2, IDS).





