Rotating Adverts with php/ajax

For this example we are going to use the ajax call script which we created before, if you haven’t, have a look at . We shall proceed, assuming you have created the JavaScript file ajax.js.

Lets start with the JavaScript. You can either choose to create your own JavaScript file or embed it in your html code. In this example we will just embed it in the code.

We will need to add a counter and set it to 1, this will be a global variable and it determines which advert we are on

var counter = 1;

next I am going to create 2 functions, loadAjax(url request, delay) and loadBannerAd(element id, maximum amount of adverts).

function loadAjax (url, t) {
var d = new Date();
time = d.getTime();
var e = (url.match(/\?/gi) == "?") ? "&" : "?";
setTimeout('loadXMLDoc("'+url+e+'d='+escape(time)+'", true);', t);
}

function loadBannerAd (id, maxcount) {
if (document.getElementById(id)) {
loadAjax("bannerads.php?id="+escape(id)+"&counter="+escape(counter)+"&max="+escape(maxcount), 4000);
}
}

You will notice that I added a time to the ajax call, I do this so it is a unique call.  I have named the ajax file to request bannerads.php

Now we are going to create the index.htm file and call loadBannerAd in the body tag with a onload event.

<!--DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<script language="JavaScript" src="ajax.js"></script>

</head>

bannerad', 3)">

<div id="bannerad">
<img src="t1.jpg">
</div>

</body>

</html>

Now to create the ajax file which we called bannerads.php

<?php

$id = $_GET['id'];
$counter = $_GET['counter'];
$max = $_GET['max'];
$counter = ($counter == $max) ? 1 : $counter+1;
$markup = "";
$markup .= "<img src='t".$counter.".jpg'>";

header("Content-Type: text/xml");

echo <<<EOT
<actions>
<action>
<method>script</method>
<code><![CDATA[
document.getElementById("$id").innerHTML = "$markup";
counter = $counter;
loadAjax("ajax/bannerads.php?id="+escape("$id")+"&counter=$counter&max=$max", 4000);
]]></code>
</action>
</actions>
EOT;

?>

we incremented counter and returned it to 1 if the counter reaches the max counted advert.

You will notice in the code element I have requested the ajax call again to put the Adverts in a loop.

For this to work correctly you will need 3 images t1.jpg, t2.jpg, t3.jpg. You can create these yourselves and then watch your adverts roll by.

techfind.co.uk


About this entry