AJAX - The Complete Reference

(avery) #1

392 Part II: Developing an Ajax Library^


<tr><td>Zip Code: </td><td><input type="text" name="zip" /> 
<img id="spinner" src="http://ajaxref.com/ch8/images/spinner.gif"
/>
<span id="validationMsg"> </span></td></tr>

<tr><td>City: </td><td><input type="text" name="city" /></td></tr>
<tr><td>State: </td><td><input type="text" name="state" /></td></tr>
</table>
</form>
<br /><br />
<div class="results">
<div id="messageLog"></div>
</div>
</div>
</body>
</html>

The server-side code used in this example is similar to the auto-search, in that it acts as a
proxy to make a call to another site. In this particular case, the site in question does not have
a published API, so we use a technique called “screen scraping” to perform the task. The
basic idea of screen scraping is that we know the format of the input via form or URL and
the general output of markup. We then extract from the HTML returned the data we are
interested in and pass it back in our Ajax response. Scraping is unfortunately a bit fragile, as
a change in the scraped page’s output format can ruin a request, and sometimes sites
excessively scraped will add in countermeasures to defeat such mechanisms. We’ll study
this idea in depth in Chapter 10, which covers advanced topics such as Ajax and Web
Services. For now, we show you the gist of the server-side program and eliminate the URL
of the scraped site to avoid reader saturation.

<?php
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: application/json");
$zip = htmlentities(substr(urldecode($_GET['zip']),0,16));
$url = "http://SITE.WE.GET.ZIP.CODE FROM/zipserch?zip=$zip";
$fullfile = file_get_contents($url);

// Get HTTP status
list($version,$status,$msg) = explode(' ',$http_response_header[0], 3);
if ($status != 200)
$matches = array("Your REST call to the Web Service returned an error
status of ". $status);
else
{//check to see if it's valid
if (strpos($fullfile, "is not currently assigned"))
$matches = array("The Zip Code $zip is NOT a valid US Zip Code");
else
preg_match('/<th>ZIP<BR>Code<\/th><\/tr><tr><td align=center>([^<]+)<\/
font><\/td><td align=center>([^<]+)/', $fullfile, $matches);
}
Free download pdf