How to do an AJAX search with jQTouch, Part 2

Jul 31, 2010

In the last installment of How to do an AJAX search with jQTouch we looked at how to setup a jQTouch interface with the goal of performing an AJAX search. In this article, we will write the necessary JavaScript to perform that AJAX search, as well as a PHP script to respond to those calls.

Before we start, we should take a step back and consider what we're about to do. Our Searcher app has three parts:

the client-side jQTouch UI,

the client-side jQuery AJAX calls,

the server-side PHP script (that could easily be backed by a database)

At this point we have finished the jQTouch UI. However, instead of immediately moving on to writing the jQuery AJAX calls, let's start with the PHP script instead. This will help us understand our AJAX calls when it comes time to write them.

The PHP Script

Since our PHP script will be performing a search, let's create a file called search.php and add a single line of boilerplate:

For files that contain only PHP code, the closing tag ("?>") is never permitted. It is not required by PHP, and omitting it prevents the accidental injection of trailing white space into the response.

Our Searcher app needs to search for something, so let's pretend it's an interface for a music player and we're searching for songs. In order to express that idea into PHP code, we need the following elements:

a Song class to hold the artist name and the title,

an array holding a bunch of Song objects,

a function for searching the Song array,

a way to get a search value from the AJAX request,

a way to set the MIME type to JSON,

a way to encode our Song array as JSON

First, we'll need a class to hold the songs (place this starting at line 3 in search.php):

at lines 22-23, we check to see if the search value is empty (i.e. an empty string or null). If that's the case, then we just return all the songs

at line 25, we declare the $matches array. This will contain all the songs that match the search value $value

at line 26, we use a foreach loop to iterate through all the Song objects in the $songs array

at lines 28-29, we check to see if the artist name or song title contain the search value $value

at line 30-31, we add the Song object to the $matches array if it matches the artist name or song title

at line 33, we return whatever matches (if any) we have found

Ok, so now we have a Song class, an array of Song objects, and a function that searches that array. What's left in our PHP script? Well, as it stands, we have no way to interface with it. What we need to do now is have some sort of way to respond to the AJAX GET request that our Searcher app will send. To do that, we harness the awesome power of the $_GETsuperglobal:

$value = $_GET['value'];
$matches = search($songs, $value);

On the first line, we extract "value" parameter from the $_GET superglobal and assign it to the $value variable. The second line runs our search function on the $songs database and searches for songs that have an artist or title that contains the $value string.

We're almost there! At this point we've managed to get an array of Song objects that match the passed search value. All we need to do now is return that PHP array of objects as a JSON-encoded array of objects. Let's do that now:

header('Content-Type: application/json');
echo json_encode($matches);

The first line sets the the MIME type of an HTTP response. MIME types are a sort of meta data that is used to describe what sort of content is being returned. In this case, we are telling jQuery (or whatever client that issued the request) that we are returning content that is JSON formatted. The second line is a built-in PHP function that converts PHP types into a string containing their JSON counterparts. Basically, it allows us to encode our PHP objects into JavaScript and allow us to access them in a nearly identical way:

And we're done the PHP script! If we want to test it, we can load execute the PHP file on our server and try different search values. For example, entering this URL should return a JSON array with two Song objects:

The jQuery AJAX calls

The finish line is now in sight. We've successfully written our jQTouch UI and our PHP script. The last thing we need to do is write some jQuery AJAX calls to execute our search and load the results into our UI. In order to do that, we need to do the following:

listen for the submission of the search form in the jQTouch UI

when the submission happens, get the search value from the form and set it as a parameter in an AJAX call to search.php

register a callback that will populate the jQTouch search results when the AJAX call completes

Let's start with listening for the submit event on the search form. First, we'll need to create a new JavaScript source file search.js and fill it with the following boilerplate:

(function($){
// Put code here.
})(jQuery);

What this boilerplate does is give our JavaScript script its own context so that can minimize leaking variables into the global JavaScript namespace. It also gives us access to the jQuery object in the convenient $ form, regardless of whether or not "no conflict" mode is enabled.

Recall in part 1 we defined an HTML search form that looked like this:

Note that on line 1 we defined the id of the form as search. We'll use that to find the form and register a handler for its submit event so that we can take action when someone tries to perform a search using the jQTouch UI.

Conclusion

In this, the final installment of How to do an AJAX search with jQTouch, we finished off the example application we started in the first part of this series.

In part 1, we covered building a UI using jQTouch. In part 2, we helped visualize our problem by pretending that we were writing a front-end UI to a server-side music player. To do that, we jumped into server side programming with PHP to write a script to serve us JSON-encoded Song objects. Once we had that setup, we moved back into JavaScript. In order to make use of the PHP script, we wrote a jQuery handler to respond to a jQTouch form submission. The handler, once triggered, issued an AJAX call to the PHP script to pull down the appropriate Song objects for display in our UI.

What Now?

With respect to the goals of this tutorial, nothing. However, if you want to pimp up the application a bit more, some things you could do are:

Add genres and albums to the PHP Song object and then make the jQTouch UI menu have two additional options: Genres and Albums

Try to make a Now Playing sub-menu that is activated when a Song is picked from the Search screen

24 comments

Edmundo Junior
Sep '10

Awesome tutorial, works great for me! Until...
There's any way to wrap up the results with a link? I'm trying to do something like this:
$songs = array(
new Song("Controle", "Neozinho"),
);
But don't work! I do not now PHP so well =/
Can you help me? What do I do?
Thanks!
Ps.: sorry for the bad english;

@Edmundo Junior:
If you want to wrap it in a link, you'll probably need to add a new field to Song (maybe called $url) and then make the jQuery code create a link if that field isn't empty.
I suggest grabbing a book on PHP :)

Edmundo Junior
Sep '10

@cdmckay I'm grabbing a book called internet right now :)
Again, excellent tutorial! Thanks for the fast reply!

morgan
Sep '10

Hi,
This code sample doesn't work for me, the search always return undefined, undefined in the result list.
It seems that this part of code doesn't work:

I put my "search.php" file in the same place as the other files.
Am i doing sthing wrong?
Thanks in advance.
Morgan

cdmckay
Sep '10

Try downloading the code that I used (and tested):
http://cdmckay.org/files/jqtouch-ajax-search-part2.zip
It may be a PHP version issue. I was using 5.3. It may not work with previous versions.

morgan
Sep '10

That's good, that was a php issue. Thank you very much! I just discovered jQTouch and webapps and your sample was very useful for me.
What would you advise me to do in order to accomplish the following:
I want to have a 3 depth cascading links in unordererd lists. I'm not sure I'm clear so I make a draft:
section1 > link1>
link2>
... > linkA > content1
linkB > content2
...
Each time I click a link, a php request to a database is made to get a list of datas that will populate my ul and will be links to launch other php requests ... until I reach a final description.
I hope it won't bother you to respond to such strange thing.
Thank you.
Morgan.

thor
Oct '10

Script doesnt work for me either, says search results are undefined, tried the other version posted but didnt help. ive been trying to make a search (without reloading the page) for 3 days now, was hoping this would be it, its almost exactly what im looking for. Good job anyways.

thor
Oct '10

So this only works with PHP 5.3? Should mention that in the tutorial, how do I display the results then? When I do alert(data) I see that its grabbed the data, but no idea how to display it. evalJSON(data) or parseJSON(data) doesn't work either.

cdmckay
Oct '10

@thor:
The JSON is already parsed. The "data" object is the JSON object.

steve
Nov '10

Is there a way to have the results appear dynamically as I'm typing? Like how iTunes search works.

cdmckay
Nov '10

@steve:
If you listened for the "onKeyUp" event (check the jQuery documentation) and fired your AJAX request then, you could simulate that behaviour.

Sebastian
Jan '11

Just thanks, well coded with clear explanations.

steven
Feb '11

Great tutorial, just one thing please...
You are currently heardcoding the results in an array and searching the results in the page.
How can I query a database instead please?
thanks

John P
Feb '11

Thanks a million. People like you make the world a better place. :-)

cdmckay
Feb '11

@steven:
You'll need to grab your records from a database and then load them into Song objects.
For example:

I'm sorry for my bad english.
Here is my question: is it possible to give the results a specified link?
example:
I would like to search for Weezer, and end up with a clickable result "Weezer - Say It Ain't So" that points me to a http://example.com
Is it possible?
Can you provide the code?
Thanks

moffie
Jul '11

I forgot to say, obviously, I would like to have a different link for each different result.
Thanks again

galo
Oct '11

Hi, thanks for the tutorial, it works. I am on a task, i dont need to search i just need to show a mysql table when i push over a button. Your tutorial almost gettin me there, how can i do this?

Kamal
Oct '11

Hi,
Nice tutorial,
Please, what did you use (tools IDE,..) to develope this example and how it was simulated ?
2)How it was reloaded the web page in iPhone or iPad ?
3) I see php here, does iPhone or ipad or a simulator understand php ?
Thanks
Your help is appreciated.

cdmckay
Nov '11

@Kamal:
I used NetBeans to develop it and used my iPod Touch to run it over my local network. The page was served using Apache via XAMPP on Windows. You are right, iOS does not natively run PHP. The PHP is run on the server side.