Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^284) CHAPTER 18 ■ AJAX AND JSON
Listing 18-9. The Server-Side Code (suggest.php)
<?php
$arr = array(
'Alpha','Bravo','Charlie','Delta','Echo',
'Foxtrot','Golf','Hotel','India','Juliett',
'Kilo','Lima','Mike','November','Oscar',
'Papa','Quebec','Romeo','Sierra','Tango',
'Uniform','Victor','Whiskey','X-ray','Yankee',
'Zulu'
);
$search = strtolower($_POST['search']);
$hits = array();
if(!empty($search)) {
foreach($arr as $name) {
if(strpos(strtolower($name), $search) === 0) {
$hits[] = $name;
}
}
}
echo json_encode($hits);
If you type a character into the resulting input box, you should see that any matching entry
will be shown. Using the same technique, you could show the results of an SQL query, such as
a username search or an account number lookup.


Just the Facts


In this chapter, you learned about Ajax and JSON. JSON interaction with PHP can be problematic
because JavaScript and PHP do not share identical data types, and what is called an associative
array in PHP is actually an object in JavaScript.
The examples in this chapter demonstrated how to use the JSON implementation from
Json.org (json.js). In the GET application, you used synchronous communications and received
the current server time through an Ajax request in response to clicking a hyperlink. In the POST
application, you used asynchronous communications and created an input box that gives
suggestions from a list of server-side data as you type.

McArthur_819-9.book Page 284 Friday, February 29, 2008 8:03 AM

Free download pdf