2. MARCO TEORICO
2.3 HIDROLOGIA E HIDRAULICA DE LA CUENCA
OK, so you’ve had a look at the code and what it looks like in its finished format; now let’s have a look at how the script works. The centralized page you load into your browser is
sample9_1.html.
Here you will note that the loadthescoresfunction is called when the page has com- pleted loading. This will populate the page with the scores initially, and then trigger the continual updates. We will look at how this function works shortly.
Two parameters are also passed into this function. The first is the date for which the scores will be obtained, and the second is the name of the divwhere the results will be displayed.
<body onload="loadthescores('2006-01-23', 'scorescontainer')"> <div class="hockeybox">
<h2>Hockey Scores</h2>
<!-- Load the Ajax response data into here --> <div id="scorescontainer"></div>
</div>
Here is the actual loadthescoresfunction itself (contained within the functions.js
file). The first thing to do is update the target element to display a loading message to the user, before initiating the Ajax request.
function loadthescores(date, container) {
// Let the user know that the scores are loading.
// Load an Ajax request into the hockey scores area.
processajax('sample9_1client.php?date=' + date, container, 'post', ''); // Then set a timeout to run this function again in 1 minute.
setTimeout("loadthescores('" + date + "', '" + container + "')", 60000); }
Take special note of the recursive setTimeout-based loadthescoresfunction call. Once you initially call the function using the onloadevent, the function will continue to call itself every 60000 ms (1 minute). By changing the last argument in the setTimeoutfunc- tion, you can increase or decrease the amount of time between score refreshes. Note that this function makes use of the runajaxfunction that you’ve been using throughout this book. It simply makes a request to the server (asynchronously) and then loads the results into the element of your choice (in this case, the loadscores div).
Now that you’ve seen how the layout works with your script, let’s have a look at the client/server setup. First, let’s have a look at the server setup so that you can see exactly what the client is calling. The server setup is contained within the sample9_1server.php
file.
<?php
//sample9_1server.php
First off is the creation of some fake game data. Obviously, if this were a “real” web service, this data would represent the actual scores in real time. This example, however, will simply use the PHP randfunction to generate the scores.
// Generate some fake game data. $games = array();
$games[] = array('date' => '2006-01-23', 'hometeam' => 'Calgary Flames', 'awayteam' => 'Edmonton Oilers', 'homescore' => rand(1, 5), 'awayscore' => rand(1, 5)); $games[] = array('date' => '2006-01-23',
'hometeam' => 'Los Angeles Kings', 'awayteam' => 'Anaheim Mighty Ducks', 'homescore' => rand(1, 5),
'awayscore' => rand(1, 5)); $games[] = array('date' => '2006-01-24',
'awayteam' => 'Calgary Flames', 'homescore' => rand(1, 5), 'awayscore' => rand(1, 5));
Now we will create the remote procedure. This is the function that users of the web service will be able to call. As you can see, this is simply a PHP function. In other words, because you are providing a web service, other people execute a PHP function without even using PHP! This function simply loops over the game data just created and checks to see if the date field matches.
// Return all of the games found for the given date. function getHockeyGames($date)
{
$ret = array();
foreach ($GLOBALS['games'] as $game) { if ($date == $game['date'])
$ret[] = $game; }
return $ret; }
Now, the PHP SOAP library must be used to create the web service. Because the library is compiled into PHP, you can use the SoapServerclass natively without the need to include any libraries. There are several ways to use this class, but just note for now that
nullis being passed as the first parameter, which means that theurioption must be specified in the second parameter.
Next, you tell your newly created SOAP server about the getHockeyGamesfunction. By calling the addFunction()method, you add this function to the web service so that it can be called externally.
// Create the SOAP server and add the getHockeyGames function to it $soap = new SoapServer(null, array('uri' => ''));
$soap->addFunction('getHockeyGames');
Finally, you need to handle a call to the web service. That is, when somebody tries to use the service, you have to detect this and then handle it. Since SOAP requests are submitted using POST, you check REQUEST_METHODto make sure that POSTwas used. Addi- tionally, it is coded so that if you load the server script directly into your browser, it will list the available methods.
// Use the request to (try to) invoke the service. if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$soap->handle(); }
else {
echo "Available functions:\n";
foreach ($soap->getFunctions() as $func) { echo $func . "\n";
} } ?>
With the server in place, it is important to host it somewhere online so that you can test it. Once the script is somewhere online, it is time to build the client script to test the access to the web service at that URL. The client script is contained within the
sample9_1client.phpfile, shown here:
<?php
//sample9_1client.php
First, you must determine the full URL where the web service is loaded. Here is a short snippet of code that will automatically detect the location of the server. You can substitute the full location of the sample9_1server.phpfile if you need to.
// Determine the location of the SOAP service
$location = sprintf('http://%s%s/sample9_1server.php', $_SERVER['HTTP_HOST'],
dirname($_SERVER['SCRIPT_NAME']));
Now, you use the SoapClientclass, another built-in class that is part of the PHP SOAP library. Here, the location of the service to connect to is passed in, as well as the name- space (specified by the uriparameter. It is required to use this class, although you’re not really using it).
Since this is a PHP 5 class, an exception is thrown if any errors occur while connect- ing to the service or calling any of its methods. To handle these, you use tryand catchin your code.
One of the best parts of the SoapClientclass is that any functions found in the service that you connect can be called as though they were native PHP functions. This allows you to directly call getHockeyGames()on the $soapobject.
try {
$soap = new SoapClient(null, array('location' => $location, 'uri' => '')); // Run the remote procedure and get the list of games $games = $soap->getHockeyGames($_GET['date']); }
catch (SoapFault $ex) {
$msg = sprintf('Error using service at %s (%s)', $location,
$ex->getMessage()); echo $msg;
exit; }
Finally, you output the games returned from the service into HTML. This data is returned via Ajax and displayed on your page. You simply loop each game and list it as a row in the table. Additionally, you are alternating background colors on each row to make the data easier to read. You simply check whether or not the row number is even or odd, and change the CSS class accordingly.
<table> <tr> <th colspan="2">Home</th> <th></th> <th colspan="2">Away</th> </tr> <?php if (count($games) == 0) { ?> <tr> <td colspan="5"> No games were found </td>
</tr>
<?php } else foreach ($games as $i => $game) { ?>
<tr<?php if ($i % 2 == 1) { ?> class="alt"<?php } ?>> <td><?= $game['hometeam'] ?> <td><?= $game['homescore'] ?> <td>-</td> <td><?= $game['awayscore'] ?> <td><?= $game['awayteam'] ?> </tr> <?php } ?> </table>
Well, that’s all there is to it. As you might expect, you can get pretty fancy and
involved on both the client and server levels. You can deal with password-protected func- tions, functions that talk to databases, and so on—whatever you like. The hard part isn’t coding the functions, it’s getting your mind around the concept of a client script talking to a server script and outputting the result to a client browser. Using Ajax, it becomes even more complex in that the result is being searched for and displayed asynchronously without the user being aware of the complex code that is being executed.
Summary
When all is said and done, I really enjoy the concept of web services with Ajax. The result is so functionally powerful, allowing developers to not only share hoards of data with the Internet community, but to display it in a very nice and convenient way for the user. The sky is the limit when it comes to this kind of functionality, and as data becomes more and more limitless, having a means to make use of another developer’s hard work becomes a crucial part of online business functionality.
Since you have seen how to create and execute your own web service–based code, you are now ready to move on to an already existing web service application. In the next chapter, you will look at and make use of one of Google’s more fun and exciting web- based services: its mapping API.