AJAX banner rotation
So here's the case: rotate ads on a website, even when the page is not reloaded. If the chances are that the visitor will spend more time on a page, it makes sense to opt-in for displaying more than one ad at one page load. I've done this in the past using iframes, but hey, it's 21st century (the last time I checked) and we have AJAX!
I also wanted to have the flexibility to display any ad type, which means I should be able to rotate pieces of HTML, rather than just images. Using HTML chunks, the ad can be an image, or formatted text, or swf, etc.
Demo
If you're curious to see the demo, go straight ahead (nothing impressive, I must admit, just rotating stuff
).
Getting busy
The "architecture" is fairly trivial - one HTML page (demo.html) and one JavaScript (ajax-banner.js) that makes XMLHTTP requests to a server-side script (ajax-banner.php). The server side (that has all the logic to figure out the next advertisement to show) returns XML response which is received by the caller JS and then displayed in a div on the HTML page.
<div id="ajax-banner"></div>
The server-side script
For the purposes of the example, the ad logic is simple - an array of HTML chunks, we pick a random one and return it as part of the XML response. In addition to the HTML chunk, as part of the XML response, the server-side script also produces an "instruction" as to how long should the ad be displayed.
Here's how the script looks like:
// an array of banners $banners = array ( '<em>ban</em>ner 1', 'banner <strong>2.0.</strong>', '<h1>big banner</h1>', 'Inline JS won't run<script>alert("boom!")</script>', 'External JS won't run
( <script src="test.js"></script>', '<img src="phpied.gif" />' ); // pick a random one $html = $banners[array_rand($banners)]; // send XML headers header('Content-type: text/xml'); echo '<?xml version="1.0" ?>'; // print the XML response <banner> <content>echo htmlentities($html); </content> <reload>5000</reload> </banner>
The javascript
The javascript consists of three functions. The main "dispatcher" is nextAd() which loads the next ad in the div. nextAd() calls the makeHttpRequest() function to send a request to the server-side script and then passes the response to loadBanner() which actually updates the banner div.
makeHttpRequest()
I've been using this simple function I came up with for a few projects (like theInvisibleAd.com) No AJAX libraries or toolkits are necessary as the task is pretty straightforward.
This function makes an HTTP request and passes the response to another function, specified on-the-fly. The function is the bare basics of the AJAX thing and if you're interested in the details you can check my article on SitePoint where I've used it to create a simple web console application.
nextAd()
This function makes the request and passes the response to loadBanner(). The HTTP request uses the current time in milliseconds to try to prevent the client browser from using a cached copy from the previous request.
function nextAd() { var now = new Date(); var url = 'ajax-banner.php?ts=' + now.getTime(); makeHttpRequest(url, 'loadBanner', true); }
loadBanner()
loadBanner() accepts the XML response generated by the server-side script. The XML has two tags - content (the HTML to be displayed) and reload (the allocated time for this ad to be displayed). The banner div is updated with the new HTML content using innerHTML the simplest, yet questionable by some purists, including myself, way of updating an already loaded page with JS.
Once the ad is updated, old timeout is cleared (if any) and a new timeout is set, the time in milliseconds after which we'll call nextAd() again to make the next HTTP request.
function loadBanner(xml) { var html_content = xml.getElementsByTagName('content').item(0).firstChild.nodeValue; var reload_after = xml.getElementsByTagName('reload').item(0).firstChild.nodeValue; document.getElementById('ajax-banner').innerHTML = html_content; try { clearTimeout(to); } catch (e) {} to = setTimeout("nextAd()", parseInt(reload_after)); }
Conclusion
There's one drawback to this method though - any javascripts (inline or external) in the ad's body won't get executed. I have a remedy for this - including JavaScripts on the fly, outlined in this posting, but in this case I need to know something about the HTML returned by the server-side script, which can be passed as another tag in the XML, saying something like <is-this-js> -> you bettcha! In this case the solution will become less of a one-size-fits-all, but still a viable option.
Overall, if you don't plan to use JS in your ads, the solution outlined in this post is very simple and seems like ideal for replacing iframe-based banner rotations using sexier AJAX.
Post this entry to: » del.icio.us » Digg » Furl » Newsvine » reddit » Y!
February 13th, 2006 at 5:21 am
[…]
Ajax13 Feb 2006 03:50 pm
AJAX banner rotation
Check this cool script “AJAX banner rotation” , Sort of Ajax version of phpadsnew but th […]
February 23rd, 2006 at 11:00 pm
Good stuff, thanks for sharing!
March 11th, 2006 at 8:10 am
test
March 14th, 2006 at 6:03 pm
Saved me a lot of work. thnx!
March 18th, 2006 at 10:31 am
Nice. I prefer this one over php rotating banners.
March 22nd, 2006 at 9:13 am
Demo page don't work.
March 28th, 2006 at 4:02 pm
[…] AJAX Banner RotationRote las publicidades de un website, incluso cuando la página no se recarga. […]
March 28th, 2006 at 4:02 pm
[…] AJAX Banner RotationRote las publicidades de un website, incluso cuando la página no se recarga. […]
March 29th, 2006 at 6:57 am
Appriciate the script, however it seems to be a problem running to diffrent banners at the same page?
April 4th, 2006 at 4:08 pm
This is great!
Now, can it be made to work with some sort of transition effect?
April 5th, 2006 at 1:22 pm
I can't seem to get the demo working. I would also be interested in this with some transition effects. I have been trying to use this with the script.aculo.us effects like this site has done.
April 5th, 2006 at 10:06 pm
Thanks for all the comments, I'll try to do some more work on the script, although it was meant more as a proof of concept, not so much as a production-ready plug'n'play thingie.
Evandro, David, I just checked the demo and seems to run OK. YOu don't say it's not working because it says "Inline JS won't work", it's just a text.
April 12th, 2006 at 7:25 am
This is great, anyone know of one that works with ASP pages (the rest of the page it needs to sit on is ASP)
April 16th, 2006 at 12:57 am
great resource…thanks
April 25th, 2006 at 9:23 am
Cool tip … i need to implement something similar myself for my blog
May 3rd, 2006 at 5:58 pm
[…] The “architecture” is fairly trivial - one HTML page (demo.html) and one JavaScript (ajax-banner.js) that makes XMLHTTP requests to a server-side script (ajax-banner.php). The server side (that has all the logic to figure out the next advertisement to show) returns XML response which is received by the caller JS and then displayed in a div on the HTML page. […]
May 19th, 2006 at 1:30 pm
The demo does not work in firefox. Aparently your script is coded to only work with the IE xml requests methods but not the mozilla ones.
May 19th, 2006 at 2:16 pm
Hey Billy, thanks for the feedback!
Just tested again with FF 1.5.0.3. and it worked. Which verison are you using?
May 28th, 2006 at 11:02 pm
Ok here's a noob question:
How can I make it so it's not random and goes in order?
May 30th, 2006 at 2:36 pm
Hi csm240,
You can keep a session variable with the index of the banners array and then increment it every time.
So just replace
$html = $banners[array_rand($banners)];
with something like (not tested, so there might be a spelling error somewhere)
session_start(); if ( !isset($_SESSION['banner_index']) // not yet set || ($_SESSION['banner_index'] == count($banners) - 1) // already at the end ) { $_SESSION['banner_index'] = 0; // start from the beginning } else { $_SESSION['banner_index']++; // increment to the next } $html = $banners[$_SESSION['banner_index']];June 8th, 2006 at 7:08 am
The demo and JS link does not work anymore.
June 12th, 2006 at 3:24 pm
Little Frog, maybe it was a temporary thing. Just tried now and the links worked. The demo even worked in the ancient IE5.5.
June 21st, 2006 at 12:00 am
Demo wasn't working for me either, until I realized I had adblock on. Once I whitelisted the page, it worked fine.
Awesome tool!
July 5th, 2006 at 4:20 pm
[…] Ajax Banner Rotation : PHPied […]
July 6th, 2006 at 10:52 am
Great tutorial. I've just ben using it in a site I'm currntly building, however, when I decided to store the banner images as BLOBs in a database IE produces some rather annoying flicker affect like its talking to the database each time it manages to load the image though my getImg.php script which just returns the blob as a jpg.
Anyone else had this problem?
September 26th, 2006 at 3:56 pm
Thank you for this wonderful script!
I just worte a little script to get banners from a database.
Connect to the databse as usual.
$query = "
SELECT
pic
FROM
banner";
$result = mysql_query($query) OR die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_NUM))
$banners[] = "";
Just in case, somebody needs this.
And yeah. IE seems to kind of reload.
October 2nd, 2006 at 9:52 am
[…] Ajax Banner Rotation : PHPied […]
October 7th, 2006 at 3:48 pm
[…] Ajax Banner Rotation : PHPied […]
October 15th, 2006 at 5:07 am
[…] Ajax Banner Rotation : PHPied […]
October 18th, 2006 at 5:39 pm
AJAX Banner Rotation - no page refreshing needed by user…
…
October 24th, 2006 at 7:10 pm
[…] Ajax Banner Rotation : PHPied […]
November 15th, 2006 at 4:41 pm
may i know the demo.html script?
i try to test the demo.html but failed
November 20th, 2006 at 4:20 am
[…] AJAX Banner Rotation Rotate ads on a website, even when the page is not reloaded. Share this page: Written by mbballard on November 20th, 2006 with no comments. Read more articles on AJAX. […]
November 29th, 2006 at 2:43 am
hi
is it possible to configure the script, that it displays the banners in order and with every reload with a different picture at the beginning… arrays like
Banner 1 Banner 2 Banner 3 … 45678
Banner 2 Banner 5… 874136
95132467
etc..
i have no idea how to change it
December 1st, 2006 at 12:26 am
Dont know if im doing something wrong or what, but when I use the script, it tends to show the style, but doesnt show anything from the $banners = array… any suggestions?
December 1st, 2006 at 12:30 am
I kinda take last post back, I put it in my webpage, and now i get a popup warning that says "There was a problem with the request. (Code:404)
December 1st, 2006 at 9:14 am
Hi Tim,
Looks like there might be something wrong with the path to your ajax-banner.php. Try putting it in the same directory as the html that calls it. 404 code is for Page Not Found.
Let me know how it goes, if you want, give me a link to the page where you tried it.
Thanks,
Stoyan
December 3rd, 2006 at 8:28 pm
ok,, sorry took so long to post,,, wife goes to college, my 3 kids go to school, and I am the unemployed bum doing alot of things for his mum…lol.. thanks stoyan…
December 3rd, 2006 at 8:35 pm
Ok, huge question, was going to upload it to my main server, dont know if works there yet,, but cant use this in a php like ban.php file, correct? has to be html? cuz, I was putting it in a file for my test page to view the banner ban.html, and pulling the information into it, saving it as ban.php… changed it to ban.htm and it works fine,,,
December 3rd, 2006 at 9:19 pm
and this wasnt exactly made for running more than one banner on the exact same page, correct? I love ajax, and this has turned me into wanting to learn more, but think I need something for my site that has alot more poof…lol…. what Id like to have, ive found, but unfortunatley it doesnt let you use more than one banner on the same page either…
all I wanted was a script,,, I work with php mostly… that took information for a banner,,, and put that banner in a rotation in a specific stop… say 728×90 in the top middle… then haveing 2 other smaller banners right next to it on both sides… say 120×90 on the top left, and top right… and have all these banners change with javascript or ajax,,, within so many seconds, not when the page refreshed… and it let me set a month to month date so when the banner is paid for by month, I can say, paid for 3 months… and it would stop that banner on that month,, and Id have to update it when the client paid… this is why im trying to learn more about this… found this exact script in javascript and php at http://www.allgigs.co.uk/Developers/index.php, but i was going to work on an administration script for it, and maybe be able to add company name, and such to the database, wich was only a text database… this is what the owner of the script sent me about it in an email…
I'm afraid it will take quite a bit of work to make it able to display more than one advert. It was only ever designed for one, so is pretty-much hard-coded that way.
As a hint: the problems are with the fact that we retrieve the DOM elements for the IMG and LINK by the fixed names "ADLINK" and "AD" - you'd need the ability to rename these - adding a number etc. Next problem will be setting the "timeout" so that they are updated according to the frequency. Last problem: you probably don't want the same ad displayed multiple times, so will need to cater for this.
December 3rd, 2006 at 9:20 pm
darn, sorry so long,,, but would like to see an ajax version just like this with php,, but try to get it to work with multiple ads per one page, and different sizes…. with php of course,, I just dont know enough about ajax, or even javascript for that matter…
thanks
December 4th, 2006 at 10:36 am
Hi Tim, the thing is that I created this pretty much as a proof of concept, not so much of a plug/play type of script. I'll try to find some time to take it to the next level, but I cannot give you any time estimates
For the html/php question, I don't see a reason why the page that contains the banners should be HTML and not PHP, should work either way.
December 4th, 2006 at 4:34 pm
lol…yea, i didnt really mean it like that,, just been trying to find ways for me to learn more myself to get to the point where you guru's have… i never got into javascript, and was hesitant on ajax,,, but then the more and more i see things that i like,,, ive been wanting to learn more,, ive been working with php for 5 years,,, and never learned how to work with flash, javascript, ajax, or other scripting languages to work along side of my php… I did get the script to work on php by the way,, and it was a path problem… I liked the script I mentioned above because I thought it was something I could work with, without having to learn javascript… but see,,,, I also learned a valuable lesson,,, If you want something,, in particular,,, your best bet is to make it yourself… then if others like it also, make it available to them,,, same thing you have done with this script,, It gives me a better understanding,,, but for someone with my mentality of working with php so long,, I try to code everything with php… kinda need a step by step… so, starting to learn some javascript for beginners now… and thats because of you,,, I like what you did,,, so,,,, time for me to learn more to… where I come from you have to move to a big city to make any money at this,,, and with no certifications, hard to get here, unless again,, big city,,,lol… you make the script the way you make things,, not for the way others would like you to make it,,, this was a tutorial to show others,,, heck,, let them make it the way they want,,, dont let me push you into something,,,lol… but,,,is nice to have someone to talk to that knows something of what your talking about,,, my wife,,, the nurse… "honey, I have no idea what php is,, what javascript is,,, can you find someone else to talk to about it,, i dont mind listening, but have no idea what the heck your saying and maybe you should be in a mental ward.." same way i feel about her nursing….lol.. thanks,,, its mostly nice to have people you can talk to that have an understanding of what your doing… I will try to work with this script, and like the idea of ajax,, but have to start with javascript first or will never understand what certain things do… and have to do it on my own… course,, if you do update this,,, ill be back to check here and there,, but still have to make my own to know what im doing… from scratch,,, doing that now in php, but learning javascript to help with that script,, learning what I need to know,, and other ideas out there…
December 4th, 2006 at 4:34 pm
Im going to have to start watching what i type,, sorry,, that wont happen again,,,
December 5th, 2006 at 5:00 pm
Hey Tim, thanks for your nice comments. I'm also explaining things to my wife, and she seems to listen very hard, probably thinking of other things at the same time, heh
BTW, there is this HTML_AJAX package from PEAR, you might want to take a look at it, as it aims to take care of the JS part for you. You do your PHP, it shoudl do the rest. In case you want to postpone diving into javascript yet. Although it's a lot of fun, it really is.
December 5th, 2006 at 5:02 pm
Forgot the URL: http://pear.php.net/package/HTML_AJAX/
December 6th, 2006 at 9:35 pm
thanks stoyan, ill try that html_ajax out.. see where it gets me… currently Ive developed a script for banners that has date-start,duration,company-name,company-email,company-phone,to-url,to-banner,alt,target in a text file,,, this way I can start, stop by month, and so far that works,,, wont show banner past set duration which is so many months, and all other info I think I would need for a client, it shows the banners, and I can deal with the monthly, just getting ready to work on the rotation of banners now,,, I want them to change every so many seconds,,, but think I might have to start out with the basic page refresh for now, till i get things straight for javascript and/or ajax…
December 6th, 2006 at 9:36 pm
Just shows the banners right now, one on top of other,,, basic output from an echo right now…
echo '';
December 27th, 2006 at 9:30 am
Exelent script for ads, thaks you from france!
December 27th, 2006 at 9:31 am
Thanks you, I will add this on my web site
Very good
December 31st, 2006 at 6:46 am
I am not good at maths, and this protection you have got me floored. Thanks for the great script.
January 2nd, 2007 at 10:17 am
Ananth, heh, yes, the math can be hard sometimes. But that's life - full of comment spammers and I need some sort of protection, otherwise I was getting like 1000 spam comments a day. Yak!
January 19th, 2007 at 9:09 am
Just to say, great resource..a very nice image script….I have linked to your page on my ajax resource site www.ajaxshack.com Hope that ok….
February 11th, 2007 at 3:15 pm
Nice script. instead of using it as a an ad rotator, I altered ajax-banner.php to have it load a dynamic chat page every 2 seconds which updates a chat page without flicker.
————————————————-
';
// print the XML response
?>
2000
————————————–
However, I have run into a strange problem. The chat page will only load 14 lines and no more. No matter how much text is on the line, the chat page will load 14 lines of chat output and then it stops. A control page shows that new additions to the chat are being added just fine, but the ajax-scripts will not display more than the 14 lines, regardless of how many extra lines of chat are added. I have verified that this is not a limitation of PHPs "file_get_contents" function. Is there some limitation in the .js file somewhere or some inhernet limitation with the technology it uses that limits the ultimate size of the file that it calls? Thanks for helping with this perplexing situation.
~~Bill
February 11th, 2007 at 6:49 pm
I have found that the above mentioned issue resides in FireFox but does not reside in IE 7. Thus, Firefox, for some reason, will allow the display through the Javascript of only approx 14 lights of output and then fails to display further content from the include page.
February 14th, 2007 at 10:24 am
Hi Bill, this sounds strange. Do you have a test page somewhere, I'd like to see it.
February 17th, 2007 at 12:01 am
[…] Ajax Banner Rotation : PHPied […]
March 7th, 2007 at 1:18 am
Hello..
I tried to run and its working… but i need help if i want to get banner from database its not working…
JS gives an errror like… Object Is Expected can anyone tell me the Solution
March 24th, 2007 at 5:09 am
I have problem to using this script at more than one time on same page?
Means if the banner display top side as well as right side
It cannot works,
Give me any suggest
March 24th, 2007 at 6:19 am
errors everywhere, headers already sent, and also echoes the php source lol
March 24th, 2007 at 6:20 am
headers already sent and echoing the php
March 24th, 2007 at 7:07 am
there was a problem with the request (CODE: 404)
why the above error?
March 24th, 2007 at 8:35 am
nice, but why can't I get it to rotate, surely this is why it's AJAX powered?
Any reply gratefully recieved
April 3rd, 2007 at 5:43 am
Anyone come up with a solution to the firefox problem?
An example can be found here: http://www.christopher-allen.co.uk
April 11th, 2007 at 11:26 pm
Thanks, Its almost like the Ajax-S slideshow, I mean the concept
May 17th, 2007 at 11:46 pm
Here is an ASP version of the script:
banner 1","banner 2.0.","big banner","Inline JS won't run
alert('boom!')","External JS won't run
","")
'Pick a random one
Randomize Timer
lrandom = Int(Rnd * (UBound(banners) + 1))
%>
5000
May 17th, 2007 at 11:49 pm
Here is an ASP version of the script:
<%@LANGUAGE="VBSCRIPT"%><%response.ContentType="text/xml"%><?xml version="1.0" ?>
<script>alert('boom!')</script>","External JS won't run
<script src='test.js'></script>","<img src='phpied.gif' />")
<%
banners = Array("<em>ban</em>ner 1","banner <strong>2.0.</strong>","<h1>big banner</h1>","Inline JS won't run
'Pick a random one
Randomize Timer
lrandom = Int(Rnd * (UBound(banners) + 1))
%>
<banner>
<content><%=response.write(server.htmlencode(banners(lrandom)))%></content>
<reload>5000</reload>
</banner>
May 31st, 2007 at 10:19 pm
Make your own Ajax loading indicators with http://www.webscriptlab.com
June 11th, 2007 at 3:46 pm
[…] Ajax Banner Rotation : PHPied […]
June 14th, 2007 at 9:15 am
Is there no way to include an External or Inline JS source? or does this take more coding, let me know if it can be done in some way, thanks and great work.
June 22nd, 2007 at 2:51 pm
[…] Ajax Banner Rotation : PHPied […]
July 14th, 2007 at 11:07 am
[…] Ajax Banner Rotation : PHPied […]
July 20th, 2007 at 9:09 pm
nice , but there is a problem to using at more than one time on same page
is there no way to include an external java script source??
July 20th, 2007 at 9:12 pm
I've just been using it in a site but there was a problem with the request (CODE: 404) why the above error?
July 28th, 2007 at 8:09 am
I've created a back end in coldfusion if anyone is interested: http://www.succor.co.uk/index.cfm/2007/7/28/Banner-rotation-via-Ajax
Thanks for the code, great work.
August 2nd, 2007 at 1:31 am
>I've just been using it in a site but there was a problem with the request >(CODE: 404) why the above error?
Could you paste your code? we will analyze it.
greetings
August 12th, 2007 at 3:38 am
Can some help me how can i make fade effect
October 4th, 2007 at 6:44 am
[…] Imran, have a quick look at this. This came out as first for the "ajax banner rotator" keyphrase __________________ dmx rgb laser projector Link Bid download free shopping cart script […]
October 6th, 2007 at 7:30 pm
PsYhlO which problem do you have? For me the Code is working great
October 9th, 2007 at 9:08 am
How can this be adapted to be used with MOSS 2007 to rotate the default top site image?
Looks great, thanks in advance!
October 9th, 2007 at 11:27 pm
[…] AJAX Banner Rotation AJAX banner rotation. Rotated banner ads and even chunks of HTML. […]
October 18th, 2007 at 2:29 pm
I need this script to rotate value click ads every minute because a user might play a game for 5 min and see the one ad. Can this be done? I will be willing to pay for help.
Ben
October 29th, 2007 at 1:39 pm
Nice script, bit insecure and unreliable, like all ajax aps.
November 1st, 2007 at 9:55 pm
hi is it possiable to get 2 or more adds out at once from it?
November 14th, 2007 at 1:10 pm
Hello
all i think best ad Rotator is Simple Ad Rotator
link : http://www.phpbuddy.com/article.php?id=4
you can add banner + add Ad and more ….. and can edit fast your banner and ads for All page
thanks
November 14th, 2007 at 2:19 pm
for show file php in html you can use tag downl
November 14th, 2007 at 2:20 pm
[code]
[/code]
November 22nd, 2007 at 7:39 pm
[…] AJAX Banner Rotation AJAX banner rotation. Rotated banner ads and even chunks of HTML. […]
November 23rd, 2007 at 3:47 pm
[…] Ajax Banner Rotation : PHPied […]
November 27th, 2007 at 1:02 am
I am not good at maths, and this protection you have got me floored. Thanks for the great script.
January 22nd, 2008 at 3:03 pm
thanks
February 4th, 2008 at 6:30 pm
Thank you..
February 29th, 2008 at 12:48 pm
Hello
how i can user an javascript ads like openads code?
March 4th, 2008 at 7:50 am
can i use adsense code with this script rotation?
March 20th, 2008 at 11:04 am
How can I make it so it's not random and goes in order using ASP? Love the Banner code
March 20th, 2008 at 11:06 am
Using ASP how can i make the banners appear in order instead of randomly? Love the Banner code
April 18th, 2008 at 3:29 pm
I just get an alert "There was a problem with the request (code 404). I copied the demo + js as is & still get the problem, in FireXox + IE.