Classic ASP and Ajax very simple Star Rating system


Classic ASP Active Server Pages Examples, code, tutorials, scriptsVery simple Ajax Star Rating for Classic ASP with Stars & image map

Years ago, I used a free ASP photo gallery that was called "DUgallery." As time went along, I added my own customizations to it.

That script set had a star rating system, but it had been created before Ajax. I recently wrote a new gallery system of my own and I wanted to allow viewers to rate the pictures again, but with Ajax this time.

I looked at several star rating systems, but most were too complicated for me to easily understand and use.

Finally, I realized that with the use of image maps and Dynamic Drive's basic Ajax script, that making a new star rating system for Classic ASP would be extremely easy.

If you try this and have any problems with it, let me know and I'll try to help.

If you use this and like it, please donate.

This script assumes 2 numeric fields in your database, one called RATING and the other called NO_RATES (number of rates). In my gallery, in the PICTURES table, I have those fields along with fields that have the image filename and so on.

Download zip file of the star gifs

Place this script in the header of your ASP page where the ratings are displayed:

<script type="text/javascript">

/***********************************************
* Dynamic Ajax Content- Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""

function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}

function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}

function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}

</script>


ASP Page on which ratings are displayed:

This is for rating on a page with a single record displayed. See version for multiple rows below.
<%

xDb_Conn_Str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="& server.mappath("yourDB.mdb")
Set MyConn = Server.CreateObject("ADODB.Connection")
MyConn.Open xDb_Conn_Str
Set rsRate = MyConn.Execute("SELECT * FROM PICTURES where PIC_ID=" & request.querystring("id"))

if Not rsRate.EOF then
x_RATING=rsRate("RATING")
x_NO_RATES=rsRate("NO_RATES")

end if

' Close our recordset
rsRate.Close
Set rsRate = Nothing

%>
<%
'
Making a link title string

If NOT x_RATING < 1 then
LinkTitle="This image has been rated "&ROUND (x_RATING / x_NO_RATES) & " stars by "&x_NO_RATES &"users"
else
LinkTitle ="This image is unrated."
end if
%>
<%if request.cookies("StarRate"&strNum)="" then %>

<!-- Set up coordinates for star bar image map -->
<map name="RatePhoto">
<area title='<%=LinkTitle%>' href="javascript:ajaxpage('update.asp?id=<%=strNum%>&rating=1', 'showrates');" shape="rect" coords="0, 2, 9, 11">
<area title='<%=LinkTitle%>' href="javascript:ajaxpage('update.asp?id=<%=strNum%>&rating=2', 'showrates');" shape="rect" coords="11, 1, 22, 11">
<area title='<%=LinkTitle%>' href="javascript:ajaxpage('update.asp?id=<%=strNum%>&rating=3', 'showrates');" shape="rect" coords="23, 1, 34, 11">
<area title='<%=LinkTitle%>' href="javascript:ajaxpage('update.asp?id=<%=strNum%>&rating=4', 'showrates');" shape="rect" coords="34, 0, 43, 11">
<area title='<%=LinkTitle%>' href="javascript:ajaxpage('update.asp?id=<%=strNum%>&rating=5', 'showrates');" shape="rect" coords="45, 1, 56, 11">
</map>
<%end if%>

<!-- Inside the following div is where our rating stars appear before and after rating -->
<div id="showrates">

<%
If NOT x_RATING < 1 then
%>
<img src="images/<%= FormatNumber (ROUND (x_RATING / x_NO_RATES), 1, -2, -2, -2) %>.gif" border="0" align="absmiddle" title="This image has been rated <%=ROUND (x_RATING / x_NO_RATES) %> stars by <%=x_NO_RATES %> users" usemap="#RatePhoto"></p>
<% End If %>
<%
If x_RATING < 1 then
Response.Write "<img border='0' src=" & "images/0.0.gif" & " title="&"'This image is unrated' usemap='#RatePhoto'" & ">"
End If
%>

</div>
 


THIS VERSION FOR RATING ON PAGE THAT DISPLAYS MULTIPLE ROWS OF RATEABLE RECORDS:

If you're displaying several rows of records, each to be rated, then you'll need to make the id names dynamic:

 

<%
'set conn = Server.CreateObject("ADODB.Connection")
'conn.Open xDb_Conn_Str
'Set cnnSimple = Server.CreateObject("ADODB.Connection")
Set rsRate = conn.Execute("SELECT ID,NO_RATES,RATING FROM PICTURES where ID=" & x_ID)
'NOTE THAT WE INCLUDE PRIMARY KEY IN THIS SQL

if Not rsRate.EOF then
x_RATING=rsRate("RATING")
x_NO_RATES=rsRate("NO_RATES")
strNum=rsRate("ID")
end if

' Close our recordset and connection and dispose of the objects
rsRate.Close
Set rsRate = Nothing

%>
<%If NOT x_RATING < 1 then
LinkTitle="This site has been rated "&ROUND (x_RATING / x_NO_RATES) & " stars by "&x_NO_RATES &"users"
else
LinkTitle ="This site is unrated."
end if
%>
<%if request.cookies("StarRate"&strNum)="" then %>

<map name="RatePhoto<%=strNum%>">
<area title='<%=LinkTitle%>' href="javascript:ajaxpage('update.asp?id=<%=strNum%>&rating=1', 'showrates<%=strNum%>');" shape="rect" coords="0, 2, 9, 11">
<area title='<%=LinkTitle%>' href="javascript:ajaxpage('update.asp?id=<%=strNum%>&rating=2', 'showrates<%=strNum%>');" shape="rect" coords="11, 1, 22, 11">
<area title='<%=LinkTitle%>' href="javascript:ajaxpage('update.asp?id=<%=strNum%>&rating=3', 'showrates<%=strNum%>');" shape="rect" coords="23, 1, 34, 11">
<area title='<%=LinkTitle%>' href="javascript:ajaxpage('update.asp?id=<%=strNum%>&rating=4', 'showrates<%=strNum%>');" shape="rect" coords="34, 0, 43, 11">
<area title='<%=LinkTitle%>' href="javascript:ajaxpage('update.asp?id=<%=strNum%>&rating=5', 'showrates<%=strNum%>');" shape="rect" coords="45, 1, 56, 11">
</map>
<%end if%>
<div id="showrates<%=strNum%>"><%
If NOT x_RATING < 1 then
%>
<img src="http://qhtimes.com/qhthome/photos/assets/<%= FormatNumber (ROUND (x_RATING / x_NO_RATES), 1, -2, -2, -2) %>.gif" border="0" align="absmiddle" title="This site has been rated <%=ROUND (x_RATING / x_NO_RATES) %> stars by <%=x_NO_RATES %> users" usemap="#RatePhoto<%=strNum%>"></p>
<% End If %>
<%
If x_RATING < 1 then
Response.Write "<img border='0' src=" & "http://qhtimes.com/qhthome/photos/assets/0.0.gif" & " title="&"'This site is unrated' usemap='#RatePhoto"&strNum&"'" & ">"
End If

%></div>


UPDATE.ASP for database work
Be sure to set the referer check to your own URL

<%
xDb_Conn_Str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="& ("C:\YourDB.mdb")


referer=request.servervariables("http_referer") 'I'm using a referer check for security reasons

if referer = "" then 
response.end
end if

refArray = Split(referer, "?")

%><%
Dim myNum
myNum = refArray(0)

Select Case myNum
Case "http://YOURURLTO/gallery.asp"
strOK = 1
Case "http://www.YOURURLTO/gallery.asp"
strOK = 1
Case "http://YOURotherURLTO/gallery.asp"
strOK = 1
Case "http://www.YOURotherURLTO/gallery.asp"
strOK = 1

End Select
%>

<%
if NOT strOK = 1 then
response.write "No permissions" 'Gives instructional error message
response.end 'stops processing
end if

%>
<%

strKey = request.querystring("id")
strRate = request.querystring("rating")
Response.Cookies("StarRate"&strKey)=strKey 'Use cookies to limit the number of times one may rate
Response.Cookies("StarRate"&strKey).Expires=date+365
'if request.cookies("StarRate"&strKey)="" then
%>

<%

' Next, the script updates the database table:


' Setting variables
Dim rs, data_source
data_source = myDSN
set conn = Server.CreateObject("ADODB.Connection")
conn.Open xDb_Conn_Str


' Creating Recordset Object and opening the database
Set rs = Server.CreateObject("ADODB.Recordset")
' Lets open table
'rs.Open "PICTURES", conn, 1, 2, adCmdTableDirect

' No rs.AddNew command needed here since we are only
' updating the records
strsql = "SELECT * FROM [PICTURES] WHERE [PIC_ID]=" & cint(strKey)
'response.write strsql
set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strsql, conn,3,3

rs("RATING")=rs("RATING")+strRate  'Adding the old field value with the new
rs("NO_RATES")=rs("NO_RATES")+1  'Adding the old field value with the new


' Now updating records

rs.Update
x_RATING=rs("RATING")
x_NO_RATES=rs("NO_RATES")
'response.write x_NO_RATES
' Done. Now Close the Connection
rs.Close
Set rs = Nothing
if err<>0 then
Response.Write("No update permissions!") 'ae_name field is primary key so new record not inserted if name pre-exists in table
else
response.write "<font size=1>Thank you for rating!</font><br>"
%>

<img src="images/<%= FormatNumber (ROUND (x_RATING / x_NO_RATES), 1, -2, -2, -2) %>.gif" border="0" align="absmiddle" title="<%=x_PIC_NAME %> has been rated <%=ROUND (x_RATING / x_NO_RATES) %> stars by <%=x_NO_RATES %> users">
<%
end if
conn.Close
Set conn = Nothing
'end if
%>

 

 


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