AJAX - The Complete Reference

(avery) #1

PART III


Chapter 10: Web Services and Beyond 487


With this process in mind, we see building a simple server proxy is quite easy. For
example, quickly read the following PHP code:

<?php
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: text/xml");
$query = $_GET["query"];
$url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_
key=XXXXXXX-FAKE-API-KEY-GET-YOUR-OWN-XXXXX&safe_search=1&per_page=10&content_
type=1&text=$query";
$result = file_get_contents($url);
/* Check response status */
list($version,$status,$msg) = explode(' ',$http_response_header[0], 3);
if ($status != 200)
echo "Your call to the web service returned an error status of $status.";
else
echo $result;
?>

We see that the php code takes the value of query and forms the URL to call, then it gets
the result and decides whether to pass the packet or send an error message.
To fully develop the example on the client side, we build a simple form to collect the
query string in question and then send it off to the proxy program. You’ll note that we make
sure to set a status indicator here as the request might take a while.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 10 : Flickr Web Service Search using Proxy</title>
<link rel="stylesheet" href="http://ajaxref.com/ch10/global.css" type="text/css"
media="screen" />
<script src="http://ajaxref.com/ch10/ajaxtcr.js" type="text/javascript"></script>
<script type="text/javascript">
function search(searchterm)
{
if (searchterm == "")
{
alert("You must enter a search term");
return;
}
var url = "http://ajaxref.com/ch10/proxyflickr.php";
var payload = "query=" + searchterm;
var options = {method:"GET",
payload:payload,
onSuccess: handleResponse,
statusIndicator : { progress :
{type: "text", text: "Searching...", target: "results" }}};
AjaxTCR.comm.sendRequest(url, options);
}
function handleResponse(response)
Free download pdf