AJAX - The Complete Reference

(avery) #1

PART II


Chapter 8: User Interface Design for Ajax 385


(gTimer);gTimer=null;};
document.requestForm.onsubmit = function(){return false;};
};

The getSuggestions() function reads the query entered and avoids making another
query if it has already been made. This could probably be made much more sophisticated in
terms of cancelling requests if the user is typing very fast or hits backspace, but the point
here is to demonstrate the pattern primarily, not to fine-tune it. Also note the unfortunate
need for global variables prefixed with the letter g to keep addressing the numerous
running queries simple.

function getSuggestions()
{
var query = document.requestForm.query.value;
if (query != gLastQuery && !gRunning)
{
gRunning = true;
document.getElementById("loadingMsg").innerHTML = "Loading...";

var url = "http://ajaxref.com/ch8/search.php";
var payload = "query=" + query;
sendRequest(url, payload, query);
gLastQuery = query;
}
}

Now we see the normal sendRequest() function shown in many previous examples,
but this time note its destination (search.php), as it will not be a canned echo statement but
will actually fetch results from the Yahoo search service. This particular PHP program acts
as a proxy for the Ajax program, calling Yahoo with the entered query and sending the
results back in a JSON-formatted response. This is just a brief preview of the use of Web
Services, which will be covered extensively in Chapter 10.

<?php
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: application/json");

$query = urlencode($_GET["query"]);
$url = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=
XXXXXXXXX&query=$query&output=json";
$rest = file_get_contents($url);
// Get HTTP status
list($version,$status,$msg) = explode(' ',$http_response_header[0], 3);

if ($status != 200)
echo "Your REST call to the Yahoo Web Services returned an error status
of $status.";
else
echo $rest;
?>
Free download pdf