Creating a Dynamic Banner System with AJAX - Completing the dynamic banner system
(Page 4 of 5 )
As you'll recall from the previous section, it's necessary to build a simple PHP script that is capable of sending back to the client the correct banner image, along with its respective URL, each time an HTTP request is triggered by the AJAX application that you saw previously.
Therefore, below I included the definition of the aforementioned script, which simply fetches the data corresponding to each banner from a plain text file named "banners.txt."
Here's how the script looks:
(definition of "fetchbanner.php" file)
<?php
try{
if(!$banners=file('banners.txt')){
throw new Exception('Error reading banners file');
}
$bannerId=!$_GET['bannerid']||$_GET['bannerid']<0||$_GET
['bannerid']>count($banners)?0:trim($_GET['bannerid']);
echo $banners[$bannerId];
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
?>
Indeed, after studying the signature of the above script, you'll grasp very quickly how it works, since all it does is read the contents of the "banners.txt" file and send the appropriate banner data back to the client.
In addition, I included below the definition of a basic "banners.txt" file, which has been previously populated with some sample banner images and a few fictional links:
(definition of "banners.txt" file)
banner1.gif|http://www.myhosting.com
banner2.gif|http://www.myphp.com
banner3.gif|http://www.myjs.com



All right, at this point you hopefully understand how the above PHP script sends a different banner to the browser each time an HTTP request is triggered via AJAX. However, I'm sure you want to see the full source code of this banner application, so you can grasp more easily how the modules of this application are linked to each other.
In the following section I'm going to show you all of the source files that comprise this application. Jump ahead and read the next few lines. I'll be there, waiting for you.
Next: Listing the banner application's full source code >>
More JavaScript Articles
More By Alejandro Gervasio