Randomly rotate images, banners, content using Classic ASP and Ajax, without page refresh. Use Classic ASP to read an XML file as a recordset. Check for secure URL or build absolute URL. Makes offsite banner links open in new window.


Classic ASP Active Server Pages Examples, code, tutorials, scriptsAjax with Classic ASP for randomly rotating banners & converting XML file to recordset with refinements for checking URLs for www and secure http & creating absolute URLs, makes offsite banner links open in new window

Sometimes you want to use a text file database. Sometimes you might need to use an XML file as a database. This demo and example code shows both how to use Classic ASP with Ajax for randomly rotating banner ads or any rotating content, without page refresh. It also shows how to use Classic ASP to convert an XML file to a recordset. Original script

This is a demo of the Ajax rotating banners that use an XML file converted to recordset as the database. 

KEEP IN MIND that Ajax and javascript are very sensitive about URLs. If you are using absolute URLs in the script, such as http://yoursite.com/tw-sack.js or http://www.yoursite.com/tw-sack.js then the script may break if you are not careful to use the same exact URL for all the file references. If you are using relative URLs, as in the example below, then it should work fine regardless of whether the viewer comes to the page with http://yoursite.com or http://www.yoursite.com, unless you are including the banner rotator from within another folder. In that case, you probably will need to use absolute URLs. Of course, you could sidestep the issue by using Iframes.


Page on which banners are displayed:

<%

'First, let's determine if the url is secure or not and get the URL
dim myServer
myServer = Request.ServerVariables("SERVER_NAME")
'gets YourSite.com or www.YourSite.com
dim strSecure,myURL,strBanrURL
strSecure="443"
if strSecure = request.servervariables("server_port") then
myURL = "https://"
else
myURL = "http://"
end if

strBanrURL = myURL & myServer
'makes either http://YourSite.com or https://YourSite.com

%>
<%

' Here we have a couple of ADO constants we need when dealing with the recordset
Const adChar = 129
Const adDate = 7
Const adFldIsNullable = 32
Const adFilterNone = 0
Const adInteger = 3

' Called without parameters; we create a new recordset, and fill it with file information

dim objRS
Set objRS = Server.CreateObject("ADODB.Recordset")
Set Session("myRS") = objRS
objRS.Fields.Append "title", adChar, 255, adFldIsNullable
objRS.Fields.Append "location", adChar, 255, adFldIsNullable
objRS.Fields.Append "info", adChar, 255, adFldIsNullable
objRS.Open
%>

<%
'xml part from http://www.vovisoft.com/xml/samples/xmldyna/part1/default.htm
dim alen, iz, atitle, ainfo, alocation, xmlDoc, objLst, noOfHeadlines
set xmlDoc=CreateObject("Microsoft.XMLDOM")
xmlDoc.async="false"

' Open articles.xml database
xmlDoc.load Server.MapPath("playlist.xml")
' xmlDoc.load "C:\Inetpub\YourSitePath\playlist.xml"
'use if hard-coded path is needed
Set objLst = xmlDoc.getElementsByTagName("track")
'track is indicator for each item in this xml file

noOfHeadlines = objLst.length

' Get title, summary tags and id attribute
set atitle=xmlDoc.getElementsByTagName("title")
set ainfo=xmlDoc.getElementsByTagName("info")
set alocation=xmlDoc.getElementsByTagName("location")

for iz = 1 to noOfHeadlines
'adding the banners to the recordset
objRS.AddNew
objRS("title") = (atitle.item(iz-1).text)
objRS("info") = (ainfo.item(iz-1).text)
objRS("location") = (alocation.item(iz-1).text)

objRS.Update

Next
objRS.Sort = "title ASC"
dim BannerCount
BannerCount = cint(noOfHeadlines)
%>
<%
If not objRS.EOF Then objRS.MoveFirst
%>
<%

objRS.MoveFirst

'Now we want a random banner
Dim rndMax,strFirstImg
rndMax = noOfHeadlines
Dim rndNumber
Randomize Timer
rndNumber = Int(RND * rndMax)
objRS.Move rndNumber

dim sMyString
sMyString = Trim(objRS("location"))


'This is to make sure we don't get msie error of secure and non-secure content mixed
'It replaces http with https if necessary


sMyString = Replace(sMyString, "http", myURL)


'now we want to allow offsite urls to open in a new window so we split banner link and compare the domain in banner to our site url
dim strUrl,urlArray
strUrl = Trim(objRS("info"))
urlArray = Split(strUrl, "/")

dim myHttp
if NOT urlArray(2)=strBanrURL then
myHttp = "<a target=_blank href="
else
myHttp ="<a href="
end if
 

'Now we build the string to display a banner
strFirstImg = myHttp & Trim(objRS("info"))& "><img border=0 src='" & sMyString & "'></a>"

%>

<%
objRS.close
set objRS = nothing
%>


<script type="text/javascript" src="<%=strBanrURL%>/scripts/tw-sack.js"></script>


<%
'prevent banner flickering to rotate the same one over and over when only one banner available our Ajax below will be loaded only if more than 1 banner
if BannerCount >1 then %>
<script type="text/javascript">

var enableCache = false;
var jsCache = new Array();
var AjaxObjects = new Array();

function ShowContent(divId,ajaxIndex,url)
{
document.getElementById(divId).innerHTML = AjaxObjects[ajaxIndex].response;
if(enableCache){
jsCache[url] = AjaxObjects[ajaxIndex].response;
}
AjaxObjects[ajaxIndex] = false;
}

function Ajax(divId,url)
{
if(enableCache && jsCache[url]){
document.getElementById(divId).innerHTML = jsCache[url];
return;
}
var ajaxIndex = AjaxObjects.length;
AjaxObjects[ajaxIndex] = new sack();
AjaxObjects[ajaxIndex].requestFile = url;
AjaxObjects[ajaxIndex].onCompletion = function(){ ShowContent(divId,ajaxIndex,url); };
AjaxObjects[ajaxIndex].runAJAX();
}


setInterval("Ajax('container','<%=strBanrURL%>bannerotator.asp')",5000);

</script>
<% end if %>
<div id="container"><% response.write strFirstImg%></div>
 



DOWNLOAD EXAMPLE XML FILE

DOWNLOAD tw-sack.js (originator's site at http://www.twilightuniverse.com/?page_id=243 )


bannerotator.asp:

<%

'First, let's determine if the url is secure or not and get the URL
dim myServer
myServer = Request.ServerVariables("SERVER_NAME")
'gets YourSite.com or www.YourSite.com
dim strSecure,myURL,strBanrURL
strSecure="443"
if strSecure = request.servervariables("server_port") then
myURL = "https://"
else
myURL = "http://"
end if

strBanrURL = myURL & myServer
'makes either http://YourSite.com or https://YourSite.com

%>
<%

' Here we have a couple of ADO constants we need when dealing with the recordset
Const adChar = 129
Const adDate = 7
Const adFldIsNullable = 32
Const adFilterNone = 0
Const adInteger = 3

' Called without parameters; we create a new recordset, and fill it with file information

dim objRS
Set objRS = Server.CreateObject("ADODB.Recordset")
Set Session("myRS") = objRS
objRS.Fields.Append "title", adChar, 255, adFldIsNullable
objRS.Fields.Append "location", adChar, 255, adFldIsNullable
objRS.Fields.Append "info", adChar, 255, adFldIsNullable
objRS.Open
%>

<%
'xml part from http://www.vovisoft.com/xml/samples/xmldyna/part1/default.htm
dim alen, iz, atitle, ainfo, alocation, xmlDoc, objLst, noOfHeadlines
set xmlDoc=CreateObject("Microsoft.XMLDOM")
xmlDoc.async="false"

' Open articles.xml database
xmlDoc.load Server.MapPath("playlist.xml")
' xmlDoc.load "C:\Inetpub\YourSitePath\playlist.xml"
'use if hard-coded path is needed
Set objLst = xmlDoc.getElementsByTagName("track")
'track is indicator for each item in this xml file

noOfHeadlines = objLst.length

' Get title, summary tags and id attribute
set atitle=xmlDoc.getElementsByTagName("title")
set ainfo=xmlDoc.getElementsByTagName("info")
set alocation=xmlDoc.getElementsByTagName("location")

for iz = 1 to noOfHeadlines
'adding the banners to the recordset
objRS.AddNew
objRS("title") = (atitle.item(iz-1).text)
objRS("info") = (ainfo.item(iz-1).text)
objRS("location") = (alocation.item(iz-1).text)

objRS.Update

Next
objRS.Sort = "title ASC"
dim BannerCount
BannerCount = cint(noOfHeadlines)
%>
<%
If not objRS.EOF Then objRS.MoveFirst
%>
<%

objRS.MoveFirst

'Now we want a random banner
Dim rndMax,strFirstImg
rndMax = noOfHeadlines
Dim rndNumber
Randomize Timer
rndNumber = Int(RND * rndMax)
objRS.Move rndNumber

dim sMyString
sMyString = Trim(objRS("location"))


'This is to make sure we don't get msie error of secure and non-secure content mixed
'It replaces http with https if necessary


sMyString = Replace(sMyString, "http", myURL)


'now we want to allow offsite urls to open in a new window so we split banner link and compare the domain in banner to our site url
dim strUrl,urlArray
strUrl = Trim(objRS("info"))
urlArray = Split(strUrl, "/")

dim myHttp
if NOT urlArray(2)=strBanrURL then
myHttp = "<a target=_blank href="
else
myHttp ="<a href="
end if
 

'Now we build the string to display a banner
strFirstImg = myHttp & Trim(objRS("info"))& "><img border=0 src='" & sMyString & "'></a>"

%>

<%
objRS.close
set objRS = nothing
%>


<div id="container"><%response.write strImage%></div>

 

 


ASP Examples Menu of Active Server Pages scripts code Classic ASP

Classic ASP Active Server Pages Examples, code, tutorials, scriptsASP Examples Menu (below*)



Active Server Pages | ASP | Scripts | Tutorials | Code | Web Programming | Examples
Active Server Pages ASP code examples, tutorials, and snippets for use in Programming interactive websites.

If you find omissions or errors let me know. I have moved these code samples to their own domain; if you find pieces missing, please let me know.
My favorite scripts site is CODANGO.

*

If any the information I've posted here has been useful to you, please donate.

Quick 'n  easy  dirty PHP script code wizard-generator

Zenphoto RSS XML feed used as data source for javascript slide show with PHP

Classic ASP to archive emails into database and save attached files to folder

PHP Image GD for thumbnails and image resizing with pathing for Windows servers

ODBC database connections for Microsoft Access MDB files with Windows 7: solution posted on this forum.

HTML5 embedded video player "Projekktor" completely skinnable with hyperlinked watermark

Edit web.config to allow Windows iis7 server to handle mp4 files or other mime types as needed

URL rewrite or make friendly URLs for iis7 Windows Server 2008 by editing your web.config file

FACEBOOK API GEEWHIZ - INTEGRATE FACEBOOK WITH YOUR WEBSITE

Use PHP to zip folders for backing up a website

Use PHP to archive emails in database and save attached files to folder

Use PHP with json to check how many hits left on Twitter API

PHP get single record from Access database without catchable fatal error message

PHP to make a bot to send automatic Twitter status updates with Abraham Williams' PHP Oauth Twitter Library

A way to use the PHP Oauth Twitter Library with your Classic ASP scripts for sending status updates

Get user's IP address location for your form results

Tutorial for registering an application with Twitter

Update your Twitter status with Classic ASP and Oauth seamlessly and invisibly without having to login to Twitter. Send status updates programmatically from a web page. PHP example too.

CLASSIC ASP: Cache your Twitter tweets in a database to keep your Twitter xml requests within the rate limit of 350 per hour / PHP VERSION

PHP: Use json to fetch Twitter followers' profiles

Index files content and insert into database for faster searches

Classic ASP with Ajax: secure URL check

Classic ASP with Ajax: referer check

Classic ASP with Ajax: a solution to the ampersand problem in querystrings

Very Simple Star Rating System for Classic ASP

Star Rating System uses CSS and JS adapated for Classic ASP from Yvo Schaap PHP script

XMLhttp with ASP to fetch and save photos from Photobucket account through RSS XML. Can be adapted for Youtube videos to import data to database.

NET image resize can be used to make thumbnails for Classic ASP

Track site visitors, get their ip address geographical data, count page views with Classic ASP

Javascript slideshow with Classic ASP to load image details dynamically from database photos table

Classic ASP with Ajax for rotating banners without page refresh and XML file converted to recordset as banner database
--Variation of the above but fetching a REMOTE XML file as the database
--Variation checks for secure URL and builds absolute URL and makes offsite banner links open in new window

True inline edit Classic ASP datagrid table database edit updating with Ajax SIMPLE EASY without page refresh!

Use Ajax with Classic ASP to preview data then update form with javascript url write

Yvo Schaap's easy inline edit Ajax: an example of using it to inline edit multiple rows of records in Classic ASP

Use Classic ASP to send text messages SMS from your website (Also shows how to use xmlhttp to post form data)

Ajax with Classic ASP for seamless, no page reload database record insertion

Nested SQL Statements to make temporary column names

Multiple records per row with paging

Display multiple records per row

Get ID of newly inserted record, Classic ASP, Access Database

Javascript timer with ASP to keep track of time expired until login expires / timeout session is up

Multiple Javascript event functions triggered from single form onsubmit

Get Querystring key names along with querystring variables

These are out of date but may still be of interest:

ASP Youtube Downloader  Version FOUR
All ASP code. Allows user client side downloads of Youtube videos. You have the option to allow files to be saved directly to your site also.
ASP/PHP video downloader (Works better than ASP for large files)

Use ASP to dynamically parse a Youtube XML playlist to render to html.

Zip up an archive file of your site for backup if you need to restore website with ASP and free Zip Component.

Zip all files in a folder into an archive or backup file dynamically by specific file extension.

Sanitize or clean price cost field for database insertion or display.

Javascript image dimensions and image file size preview.

Put recordset into array, assign keys to the records then use record associated with specific array key as a variable elsewhere.

Access Database Interface Generator Wizard to read your table and field names and to create a table display.

Combining dropdown selection box menu with dynamic ASP database page.

How to redirect user to original page they tried to view before logging, after they are logged in.

Previous/Current/Next Records, or Buddy Ring Script

Custom ASP 404 page not found error script: can also be used for URL rewriting

ASP Example: Combine ASP with Javascript for popup windows
dynamically sized to image dimensions.

ASP Example: How to use ASPJPEG to create thumbnails
Click for free Highly recommended thumbnailer for which you don't need Server access (doesn't seem to work on Windows Server 2008)

ASPjpeg: How to re-scale aspect ratio of thumbnails by height instead of width.

ASP Example: What if your host has an older version of ASPJPEG that doesn't support gifs?

Select Count Distinct Records for Access Database

Upload Image to folder and insert filename into database

Get date in such a way that it can be made part of a file name

Isolate a file name away from its path or extension or strip a path from a file name or strip characters from database field

User-customized on-the-fly stylesheet css files

Enhanced Page Hits Counter (also counts downloads and menu link hits)

Loop through array and compare to string with select case

Aphabetical Paging for your ASP scripts

Web Wiz Guide's Site Searcher Script modified as a file content indexer

Let Users Select How Many Records to View

Access Database for your PayPal IPN scripts

Miscellaneous collected code

From Classic ASP to PHP

You don't have to be a genius, just persistent, to write original Active Server Pages scripts

BuildApp - great old Classic ASP script generator!

Software Recommendation: bare_bones_no_bells_and_whistles_asp_code_generator_database_interface_maker (For PHP I recommend EasyGen.)

If any of this information is helpful to you, please consider donating with the button below. Thanks! ~~Lil