Storing Banner Data in MySQL Tables for a Dynamic Banner System with AJAX - Completing the banner application
(Page 4 of 4 )
As I stated in the section that you just read, it's necessary to build a simple PHP script that retrieves the banner-related data from the "banners" database table previously defined, and then sends it back to the browser for further processing.
However, while all these tasks are certainly very simple to perform, there's one question that remains unanswered: how will the PHP script in question know which row to fetch from MySQL, if the functionality of the client-side module of the application is reduced to requesting the same "fetchbanner.php" file with AJAX, over and over again?
Well, there are many ways to tell the script which banner to retrieve from the pertinent MySQL database table, but in this case I'm going to use a simple session variable for tracking the ID of the banner that needs to be displayed. Does this sound a bit confusing? It is not, actually.
Please take a look at the following code sample, which should help dissipate any doubts:
try{
session_start();
if(!$_SESSION['id']||$_SESSION['id']>2){
$_SESSION['id']=1;
}
else{
$_SESSION['id']++;
}
$id=$_SESSION['id'];
if(!$db=mysql_connect('host','user','password')){
throw new Exception('Error connecting to
MySQL');
}
if(!mysql_select_db('banner_database')){
throw new Exception('Error selecting
database');
}
if(!$result=mysql_query("SELECT image,url FROM
banners WHERE id='$id'")){
throw new Exception('Error performing
query');
}
while($rows=mysql_fetch_array($result)){
echo $rows['image'].'|'.$rows['url'];
}
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
Now, do you see how easy it is to build a PHP script that fetches a different banner from the sample "banners" database table and, at the same time, keeps track of its ID? I bet you do! Naturally, as I said before, there are many other methods you can use to achieve the same result, but the one shown above is indeed very straightforward and also simple to implement.
Finally, having explained how the previous script works, I'd like to provide you with the complete source code corresponding to this banner application, this time including all the modifications that you saw earlier.
Here are the respective signatures for the modified source files:
(definition of "dynamic_banner.htm" file)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1" />
<title>AJAX-Driven Dynamic Banner System</title>
<script language="javascript" type="text/javascript">
// send http requests
function sendHttpRequest(url,callbackFunc,respXml){
var xmlobj=null;
try{
xmlobj=new XMLHttpRequest();
}
catch(e){
try{
xmlobj=new
ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
alert('AJAX is not supported
by your browser!');
return false;
}
}
xmlobj.onreadystatechange=function(){
if(xmlobj.readyState==4){
if(xmlobj.status==200){
respXml?eval
(callbackFunc+'(xmlobj.responseXML)'):eval
(callbackFunc+'(xmlobj.responseText)');
}
}
}
// open socket connection
xmlobj.open('GET',url,true);
// send http header
xmlobj.setRequestHeader('Content-Type','text/plain;
charset=UTF-8');
// send http request
xmlobj.send(null);
}
// display banners
function displayBanner(bannerData){
// parse banner data
var bannerImg=bannerData.split('|')[0];
if(!bannerImg){return};
var bannerUrl=bannerData.split('|')[1];
if(!bannerUrl){return};
var bannerCont=document.getElementById
('bannercontainer');
if(!bannerCont){return};
// clean up banner container
bannerCont.innerHTML='';
// create banner link
var a=document.createElement('a');
a.setAttribute('href',bannerUrl);
// create banner image
var img=document.createElement('img');
// set banner image dimensions
img.setAttribute('src',bannerImg);
img.setAttribute('width',180);
img.setAttribute('height',400);
// append banner image to link
a.appendChild(img);
// append banner link to container
bannerCont.appendChild(a);
// fetch banner recursively
setTimeout("sendHttpRequest
('fetchbanner.php','displayBanner')",15*1000);
}
window.onload=function(){
if(document.getElementById &&
document.getElementsByTagName && document.createElement){
// fetch first banner
sendHttpRequest
('fetchbanner.php','displayBanner');
}
}
</script>
<style type="text/css">
body{
margin: 0;
padding: 0;
background: #eee;
}
h1{
text-align: center;
font: bold 24px Arial, Helvetica, sans-serif;
color: #000;
}
#bannercontainer{
text-align: center;
width: 180px;
height: 400px;
margin-left: auto;
margin-right: auto;
background: #fff;
border: 1px solid #000;
}
#bannercontainer img{
border: none;
}
</style>
</head>
<body>
<h1>AJAX-Driven Dynamic Banner System</h1>
<div id="bannercontainer"></div>
</body>
</html>
(definition of "fetchbanner.php" file)
try{
session_start();
if(!$_SESSION['id']||$_SESSION['id']>2){
$_SESSION['id']=1;
}
else{
$_SESSION['id']++;
}
$id=$_SESSION['id'];
if(!$db=mysql_connect('host','user','password')){
throw new Exception('Error connecting to
MySQL');
}
if(!mysql_select_db('banner_database')){
throw new Exception('Error selecting
database');
}
if(!$result=mysql_query("SELECT image,url FROM
banners WHERE id='$id'")){
throw new Exception('Error performing
query');
}
while($rows=mysql_fetch_array($result)){
echo $rows['image'].'|'.$rows['url'];
}
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
Final thoughts
Unfortunately, we've come to the end of this series. As you saw in this group of tutorials, the functionality provided by AJAX can be used in all sorts of clever ways to develop seemingly complex web applications, with minor hassles.
So, if you're planning to set up for your own web site a system that displays different banners in a predefined time sequence, then the application shown here might be quite useful to you.
See you in the next web development tutorial!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |