I have updated the code to v2.3 to fix some problems with “countOneHitPerUser”, “countOneHitPerUserPerDay” and “oneRatingPerUser” setting not working. Thanks to Jeroen for pointing this out.
April 23. 2013
I have updated the code to use spjs-utility.js and to support newer versions of jQuery. I have tested with v1.91. v2.0 has not been tested.
04.09.2011
I have changed code to allow turning off the star-rating function. The version number is 2.1.
The file “HitCounterAndStarRatingForSharePoint.js” and the CEWP code has changed.
I have redone the Hit counter for SharePoint and changed from a simple “Like” to a star-rating.
I have done a total rebuild of the code and this new release will perform better in lists with a large number of hits.
Note: If your pages will have more than a few thousand hits, you most likely would want to hide the “hitcount” from the users. This has to do with the fact that rendering the number of hits in the browser requires the data to be pulled down to the client for counting.
As an example, 8000 “hits” will be a 2-3MB download to the client just to display the itemcount.
If you hide the counter from the user, you can still display the itemcount by looking at the “HitCounter-list” directly.
I would love to have a webservice that could return the itemcount from a given CAML query without having to pull down the entire XML-blob to the client. If someone has the knowledge to make such a webservice i would be more than happy to make it available here.
Here how it could look like in a blog:
How to setup the solution:
Step 1:
Create a list to hold the ratings. This list could be shared by all sites in a site collection if you point to it in the CEWP configuration option “counterListBaseUrl” and ensure all site users have write permission. The list should have these fields:
Step 2:
Download the code for the file “HitCounterAndStarRatingForSharePoint.js” and the images from here, and spjs-utility.js from here
Put them in a document library where all users have read permission. If you are using SharePoint Designer you could put the files in a folder on the site collection root for safe storage.
Step 3:
Insert a CEWP with this code where you want the hitcounter/rating to appear:
Updated with reference to spjs-utility.js
<span id="hitAndLike"></span> <script type="text/javascript" src="/test/English/Scripts/HitAndStar/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="/test/English/Scripts/HitAndStar/spjs-utility.js"></script> <script type="text/javascript" src="/test/English/Scripts/HitAndStar/HitCounterAndStarRatingForSharePoint.js"></script> <script type="text/javascript"> var argObj = {counterListName:'HitCounter', counterListBaseUrl:'/test/English/Blog/', countHits:true, hitCounterVisible:true, countOneHitPerUser:false, countOneHitPerUserPerDay:false, hitSuffix:['Hit','Hits'], isDispForm:true, activateRating:true, starImageSrc:['/test/English/blog/Scripts/HitCounter/star_off.gif', '/test/English/blog/Scripts/HitCounter/star_on.gif', '/test/English/blog/Scripts/HitCounter/star_selected.gif'], starCount:5, starMouseoverArr:['Very poor','Poor','Good','Very good','Fantastic'], oneRatingPerUser:false, ratingCountSuffix:['Vote','Votes'], alreadyRatedMouseover:"You have already given this item {starCount} stars!", debug:false}; hitCounter(argObj); </script>
NOTE:
Change the script src to reflect the location of your local file.
Note for SharePoint 2010 users:
You cannot put this code in the CEWP directly because of a “bug” in how the CEWP content is handled when editing the page. It basically incorporates the HTML generated by the script and thus corrupts the CEWP code.
To overcome this you must put the CEWP code in a text-file alongside the file “HitCounterAndStarRatingForSharePoint.js” and linking to it using the “Content link” option in the CEWP.
Configuration option:
- counterListName: The GUID or the “DisplayName” of the hit counter list.
- counterListBaseUrl: The baseUrl of the “HitCounter” list.
- countHits: true or false. If false, no hits are recorded. Use this setting if you want star rating only.
- hitCounterVisible: true or false. If false, the item count is not displayed to the end user. This setting is recommended if you expect a lot of hits and/or your users are on a low bandwidth connection. See note in the top of the article.
- countOneHitPerUser: true or false. If true, only one hit will ever be recorder for an unique user. If false (and the next parameter also is false) all refreshes of the page will record a new hit in the “HitCounter” list.
- countOneHitPerUserPerDay: If true, only one hit per day will be recorded for any unique user.
- hitSuffix: An array with the hit suffix in singular and plural form.
- isDispForm: true or false. If true, the item ID will be used to distinguish between records in the “HitCounter” list.
- activateRating New in v2.1: true or false. Turns the star-rating part on or off.
- starImageSrc: An array containing the relative URL to the 3 images representing the statuses “off”, “on” and “selected”.
- starCount: The number of stars in you “rating control”. You can have as many as you like.
- starMouseoverArr: An array of strings describing the rating steps. The text is displayed on mouse over on the star.
- oneRatingPerUser: true or false. If true, one user can rate an item once.
- ratingCountSuffix: An array with the rating suffix in singular and plural form.
- alreadyRatedMouseover: The mouseover if a user has already rated an item. The text “{starcount}” will be replaced with the users rating.
- debug: true or false. If true, a debug section will be displayed in the top of the screen providing all the configuration options and all variable used by the solution.
Learn how to find the list GUID or the ListBaseUrl
This solution is tested in SP2007 and in SP2010 with IE9.0, Firefox 4.0.1 and Chrome 11.0.696.68.
I hope you all enjoy this code and please report any bugs in the comment section below.
Regards
Alexander
PS!
If you like this solution, please consider donating a few dollars to fund some flowers to my wife who must endure my continuous blogging…
You Sir are a Legend, Thanks Mate.
Thank you!
Alexander
Absolutely agree, you are a master. Is there a simple way to view the rating in the list view for each item or is this only set up to view when item is open?
Hi,
The rating is available only when item is open. To have it render in a list view would require another “solution” to be made.
Alexander
Hi Alexander,
I am getting an error message when I open my page in IE8.
“Internet Explorer cannot oprn the Internet site [sitename].
Operation aborted”
Thank you for putting this together and sharing it – incredibly helpful post – useful debug help – excellent stuff!
I’m also getting the IE8 error. Any ideas?
Hi Alex, I use your solution in my development/production server & it’s working..but there is a problem with certain user which it will block them from accessing my site..most of them use IE but when I install an Firefox for them seems it’s working & they can access to the site…I did upgrade their IE version to 8 but the problem still there..
That’s happen to certain user only but my IE v8 is ok. What could possibly wrong with their IE??
Another question is, how do I get the same rating function as the one you user with thumb up & down on it…care to share with me???
Hi,
I have tested it in IE8 with no issues. You could try to reset IE to default (Tools – Internet Options – Advanced – Reset Internet Explorer settings)
Here is another rating solution
Alexander
Hi A, I had the same problem with the Star Rating. Go to load the page using IE8 and “Internet Explorer cannot open the Internet site http://.com. Operation aborted”.
It was working fine on my WinXP 32bit, then I upgraded to WinXP 64bit and whenever I used IE8, page wouldn’t load. Uninstalled IE8, installed IE7, same error, so I had to turn off the web part. I did also have your Hit Counter web part on the same page…?
It’s funny because this link http://support.microsoft.com/kb/927917 says the error doesn’t occur with IE8.
The cause is unknown because my computer also installed with the same IE8 as the others but I didn’t encounter this problem, it’s not affecting all the user no matter they use IE6/IE7/IE8 version, some may be able to access & some may not. It work perfectly in Firefox so in order to let them accessing the page, I have to let them use Firefox instead. I can’t explain why this happening… 🙁
Hi Alex, I found the reason why its happening. Its my bad actually & forgive me, your code is fine & brilliant. It was me forgot to configure the permission for sharepoint list used in this script, I’m supposed to at least give permission to all user able to add/update the data. Thats solve the problem for now. For the rest of you out there, please double check the permission on sharepoint list 1st.
But I found another issue, when I try to use the same script for another webpart in the same page, I got notification saying some line got error & the script not working on the webpart. At least, I want it become like your site here where each post/comment got its own hit/rating on it.
Hi,
This solution identifies the “hit” by the page URL and you can therefore NOT have multiple counters in one page.
Alexander
I tried to use it for anonymous user and it keep on requesting me to enter user id and password. Is this script work for anonymous user? Thanks!
Sorry, it will not.
Alexander
I’m testing your Hit Counter in a lab environment with MOSS 2007, I’ve followed the instructions literally but the CEWP do not show anything, appears like minimized, ani idea?
Hi,
Did you set the “debug” property to true?
Alexander
Great post. Works fine
Hi Alex, thanks for this updated version! You’re genius…
Thanks again to you, I got an idea now how to create a site usage report base on your program. You save my day man…….current Sharepoint site usage report won’t help me to much but by manipulating list of this Hits&Rating script, I found the solution at last.
* I still notice there is some performance issue, but with this updated version you already give us an option to turn off the hits count where its really work.
Thanks again, wish I can meet you someday.
Hi Alex,
Fan of the old Hit and Like counter and moving to this on. I have however been having issues with what fields to create in the list. Are you able to repost the image showing the required fields, as it seems to have dropped off from your site.
Hi,
Glad you like the solution.
I cannot see any missing images? – they are all there when i view the page. Here is a direct link to the image showing the fields: https://usercontent.one/wp/spjsblog.com/wp-content/uploads/2011/05/hitandratingforsharepoint_hitcounterlist.png
Alexander
Hi Alex,
Thanks for that. I really should have tried this 1st but, it seems my browser at work is not showing them but the trusty smart phone is!
Greatly sorry. Thanks for the awesome work!
Hi Alex,
I want the facility where people can rate an item more than once. This will ideally update the previous rating to the current rating. Where do I start to acheive this.
Hi,
Using the parameter “oneRatingPerUser” you can control whether the user can rate multiple times. Updating the previous rating is a bit harder and would require some changes to the code. I’ll make a note in my to-do list and see if i can find the time.
Alexander
Excellent script. I love the concept here, I just can’t seem to get past this error: Error:
An error occured! Please verify “counterListName” and “counterListBaseUrl”.
I know I must be doing something wrong. I created the list above exactly like you mentioned and named it “ratings” Here is what I have for those two fields:
counterListName: ‘EFD57F57-C575-4DD1-ABBB-453340DE6752’
counterListBaseUrl: ‘http://epss/sites/EPIT/ClientServices/FieldITC/Knowledge/Lists/ratings/’
Okay, sorry for my impatience. I figured out that I was using the viewname as opposed to display name and the baseurl was wrong. Got it working! It is awesome, just that I can’t use the commentbox with it because they conflict. So it’s either comments or stars… I chose stars unless you know of a way to get around this and use both on them same page.
Hi Jay,
I had the same issue as you mentioned. Here’s how to make the two solutions work together.
ISSUE
The problem is that both solutions use the argObj variable to store their configuration.
WORKAROUND
Open the HitCounterAndStarRatingForSharePoint.js in any editor and replace all occurences of “argObj” with “argObjStar”. (Search & Replace). Save the file.
Secondly in the content editor webpartfor the star rating webpart replace all occurences of “argObj” with “argObjStar”.
Done. enjoy.
Regards
Basil
i have same problem with you..do you have got solution..?
I implemented this on a test site and we’re properly writing to the tracking list when the page (list item) is viewed and when a vote is made.
However, it doesn’t appear to be reading from the tracking list. Where it should be showing the hit count and number of votes, it simply says “undefined Hits” and “undefined Votes”.
Any ideas?
Hi,
Are you using the latest version of this solution? – and which browser are you using?
Alexander
Alex,
I am also getting the error “Internet Explorer cannot open the Internet site [sitename]. Operation aborted”
This error shows up randomly for a few users within my organization. Is there a fix to this issue? I don’t want to tell them to just use firefox.
thanks,
BK
Sorry, but i have not been able to reproduce this error and therefore cannot tell why it happens.
Alexander
Alex,
I like the little blue icon next to your rating system showing “Most Popular Content” Do you have a process to create this?
heh – well I guess I should sign up for polldaddy, ey? This would be a good time to have a delete feature so i can delete the above comment…. 🙂
Hi Alex,
Thanks a bunch for this…really great stuff.
I’m having an issue with this feature when I also include your Comments solution on the one page. The star rating function just doesn’t want to work/write to the list. It allows you to click on a star to rate, but you refresh the page and it shows 0 votes. I’m assuming it’s to do with conflicting scripting, but can’t figure it out. Any ideas?
Cheers,
John
Hi,
I’m sorry, but i have not had the time to ensure cross compatibility with all my scripts. I’ll put this on the to-do list, but cannot guarantee anything.
Alexander
Hi John,
I had the same issue as you mentioned. Here’s how to make the two solutions work together.
ISSUE
The problem is that both solutions use the argObj variable to store their configuration.
WORKAROUND
Open the HitCounterAndStarRatingForSharePoint.js in any editor and replace all occurences of “argObj” with “argObjStar”. (Search & Replace). Save the file.
Secondly in the content editor webpartfor the star rating webpart replace all occurences of “argObj” with “argObjStar”.
Done. enjoy.
Regards
Basil
Hi,
First, sorry for my english, isn’t my native language. 🙁
I found an issue. In Chrome, HitCount variable has no value; because jQuery selector within XML reading is not cross-browser solution.
I change “[nodeName=’rs:data’]” to “rs\:data, data” instead.
Therefore, all lines where “[nodeName=’rs:data’]” is used are now:
result.count = $(data).find(“rs\:data, data”).attr(“ItemCount”); // to get list items count.
Great work with this script…
Regards.
Just wondering if anyone has got this to work on multiple posts on the default blog view. I just need it for the rating functionality not the hit counter. I currently created a custom blog.xsl that includes the id reference call too hitAndLike but it only effects my first post although it does generate the reference to each post it does not generate the code.
Any ideas or suggestions would be greatly appreciated.
hi I have added the code as described for SP 2010. However i am getting an error. The stars appear and instead of a zero votes on a new page it is saying undefined. after i have voted it say NaN. when i refresh the page it is back to undefined. The ratings list is capturing all the vote and the rating value still somehow its not averaging them up. Please help
I am sorry. I just realised I was using jquery 1.7.1 and it caused the issue. I changed it to this 1.6.2 version and it worked as usual.
hi, appreciate if you can help me out a bit.. is my code correct? because i added the CEWP,but when i exit the edit mode, nothing appears, just a blank section.. please please please help. 🙁
var argObj = {counterListName:’HitCounter’,
counterListBaseUrl:’/sites/ConsumerOpinions/RatingForSharePoint/’,
countHits:true,
hitCounterVisible:true,
countOneHitPerUser:false,
countOneHitPerUserPerDay:false,
hitSuffix:[‘Hit’,’Hits’],
isDispForm:true,
activateRating:true,
starImageSrc:[‘/sites/ConsumerOpinions/RatingForSharePoint/star_off.gif’
‘/sites/ConsumerOpinions/RatingForSharePoint/star_on.gif’,
‘/sites/ConsumerOpinions/RatingForSharePoint/star_selected.gif’],
starCount:5,
starMouseoverArr:[‘Very poor’,’Poor’,’Good’,’Very good’,’Fantastic’],
oneRatingPerUser:true,
ratingCountSuffix:[‘Vote’,’Votes’],
alreadyRatedMouseover:”You have already given this item {starCount} stars!”,
debug:true};
hitCounter(argObj);
I noticed that you may get a blank screen if the ajax functions start before the page finishes loading. To fix this, comment out the line that says “hitCounter(argObj);”
and
replace with:
$(document).ready(function() {hitCounter(argObj);});
That will make the code wait till the document is finished loading before making any modifications to the document.
Great script!
I noticed you mentioned that the script pulls the entire list of items for a given url to get the item count.
I took a look at the code and noticed that you were using ViewFields for the ratings, but not for the item count.
If you sepcify that you only want the ID field from the list in your SOAP query, then you can significantly reduce the amount of data transferred to get the item count.
The change would be simple:
In the spjs_QueryItemCount function:
Change the line that reads:
var content = spjs_wrapQueryContent({‘listName’:argObj.listName,’listBaseUrl’:argObj.listBaseUrl,’query’:argObj.query,’viewName’:argObj.viewName});
To:
var content = spjs_wrapQueryContent({‘listName’:argObj.listName,’listBaseUrl’:argObj.listBaseUrl,’query’:argObj.query,’viewName’:argObj.viewName, viewFields:[‘ID’]});
Hi, This might help a little bit, but still you will have to pull down all the lines, and the data “blob” will still be significant if you have many items returned by the query.
Alexander
Hi Alexander,
first of all – thank you for the effort that you have spent in this functionality. I tried to follow all your instructions and was able to get the following parts running:
–> Hit-Counter list is created and item are created whenever a user does hit the page
–> start and counter is displayed on my blogsite BUT:
The counter and the average rating always display a ‘-1’, also the rating column is never updated although I did ratings sometimes.
As far as I understand this is not a problem of the configuration that is done in the CEWP. These are my settings displayed when I set debug to ‘True’:
counterListName:counterListBaseUrl
counterListBaseUrl:/content/20001288/blog/
countHits:true
hitCounterVisible:true
countOneHitPerUser:false
countOneHitPerUserPerDay:false
hitSuffix:Hit,Hits
isDispForm:true
activateRating:true
starImageSrc:/content/20001288/blog/scripts/star_off.gif,/content/20001288/blog/scripts/star_on.gif,/content/20001288/blog/scripts/star_selected.gif
starCount:5
starMouseoverArr:Very poor,Poor,Good,Very good,Fantastic
oneRatingPerUser:false
ratingCountSuffix:Vote,Votes
alreadyRatedMouseover:You have already given this item starCount} stars!
debug:true
Thanks for your help!
Best – Matthias
Hi, Do you use the latest version (2.1)? Is the “hitCounterList” placed in the same site as the list you want to use it in? Which browser are you using? – could you try using another browser for reference? Which version of jQuery are you referring in the CEWP?
Alexander
Hi Alexander, thank you for the quick response! Here my answers:
(1) Yes, I use version 2.1.
(2) The “hitCounterList” is on the same site
(3) I tried IE 8 and Firefox 12 (what I recognized it that in my ‘hitcounterlist’ it always displays IE 7 (what is not correct)
(4) I am referring to 1.6.2 as you have done it in your configuration.
Just to ensure that we are on the same page… The list “hitcounterlist” is updated, just the column rating is not working. In addtion the rating and the counter on the blog site is displayed but not updated
Thanks – Matthias
have you ever tried this on a publishing site using a CQWP to show articles? I suppose in my XSLT I could pull the ratings from the list that holds the articles and have JQuery do the rest.
I implemented your solution but i am not getting star gifs. Although i get very poor, poor etc when i hover mouse where image should be coming. I use IE7.Thanks in advance
Hi,
I’m just curious if CQWP can use the countHits values, sort and return the values. That would def. deserve some beers!
Thanks.
This is Great! But, I’m getting undefined Hit and undefined Vote. Can you help?
Thanks!
Did you solve the issue with undefined ratings and hits?
Hi all,
I’m going through unanswered questions from the past months, and if any of the above is still relevant, please repost the question.
Alexander
Hi,
The star images loads perfect, but I only get the Total hits = undefined and also Total number of ratings = undefined. Did I miss anything?
What version of JQuery are you using? I’ve been working on something with this great counter (Thanks Alexander). I got those errors with j query 1.7 and above but when I rolled it back to the 1.63 library, everything worked good as gold. Hopefully this will be helpful for a short term fix for you.
I get the number of total hits correct, but the number of votes always = 0, even then i push the star .. permissions to the list granted but where only Hit items, no one vote
This feature doesn’t work when you use 2 CEWP. In my case they are: CommentBox and HitAndLike
I get a huge error message at the top of the page, shown here:
[Hit counter debug]
Error:
An error occured! Please verify “counterListName” and “counterListBaseUrl”.
Configuration
counterListName:HitCounter
counterListBaseUrl:http://pa-sps1/sites/BallardSpahr/ren/Lists/
countHits:true
hitCounterVisible:true
countOneHitPerUser:false
countOneHitPerUserPerDay:false
hitSuffix:Hit,Hits
isDispForm:true
activateRating:true
starImageSrc:http://pa-sps1/sites/BallardSpahr/ren/Scripts/star_off.gif,http://pa-sps1/sites/BallardSpahr/ren/Scripts/star_on.gif,http://pa-sps1/sites/BallardSpahr/ren/Scripts/star_selected.gif
starCount:5
starMouseoverArr:Very poor,Poor,Good,Very good,Fantastic
oneRatingPerUser:false
ratingCountSuffix:Vote,Votes
alreadyRatedMouseover:You have already given this item {starCount} stars!
debug:true
Variables
userId: 296
urlDir: /sites/BallardSpahr/ren/default.aspx?ID=
refURL: http://pa-sps1/sites/BallardSpahr/ren/default.aspx
Total hits: -1
Total number of ratings : -1
Rating average :
isHit by current user: false
isRated by current user: false
Current user rating:
Hi,
As the error message states, either the “counterListName” or the “counterListBaseUrl” is wrong.
In this case, you have the counterListBaseUrl wrong, use “/sites/BallardSpahr/ren”
Alexander
Hi Alexander,
First of all, your code is amazing and I’m learning a lot about Sharepoint thanks to you. Unfortunately, I’m running into a problem with this particular code and IE8, involving an HTML parsing error that the causes the rest of the page not to load. There’s a bunch of websites that document this same problem, including this one on Microsoft’s forums: http://answers.microsoft.com/en-us/ie/forum/ie8-windows_vista/html-parsing-error-kb927917/c80bcdb2-505a-447a-bb49-206ba6df44f1
Apparently it involves a security bug, and the way around it is to install the Cumulative Security update.
I’m wondering if you’ve encountered this problem and found a way around it? Obviously it would be best to just do the update, but I’m thinking about folks who are not saavy enough to do that. Thanks in advance for whatever advice you may have.
This is amazing and works perfectly! Thank you so much. One small thing I would like is for the Hit Counter List to show me the Title of the item, rather than the ID (or as well as). Is this possible to achieve?
Matthew,
I am also interested in displaying the ‘Title’ of the item. Did you figure out how to do it?
Good Stuff… Works perfectly with JQuery 1.6.2. When using JQuery 1.9.1, it fails. 🙁
Related to the issue above… when using this hit-counter-and-star-rating-for-sharepoint with the https://spjsblog.com/2011/07/11/commentbox-for-sharepoint/ are there conflicts with differing versions of the spjs utility functions? Please advise.
Hi,
These two solutions have not been designed to work together. The comment box solution must be redesigned to incorporate the rating. I currently do not have time to do this, but if you make a go at it, and succeed, I could post the code here.
Alexander
Has anyone found out what to modify to get this work work with jquery 1.7 or 1.8? Its not throwing an errors just returns undefined hits.
I have no choice I need to have jq 1.7 on my site cant go down to 1.6 but I would like to use this
Hi,
I have updated the code. Please note that you now have to refer spjs-utility.js.
Alexander
Love this hist counter! Been using it for a while no problems. I decided to create a second hit counter for certain pages and so I created the list, set the permissions as required and modified a copy of the script to point to the new list. For some reason the hits are not writing to the the new list and it always displays 0 viewes. I’ve double checked everything and all seems to be fine. Any suggestions?
Thanks!
Ken
Hi,
You do not need to add another list to store the hits as all hits are stored using the url of the page as identifier. Just load the CEWP code from another pager with the exact same code.
Alexander
Hi,
Great code thanks. A few things:
– can’t get it to work with jQuery higher than 1.8.3 on IE8, getting javascript errors
– I found a few issues using it in my environment, see below
1) line 216, removed single quotes around the 1, otherwise it didn’t know user already rated:
if(ratingRes.count===1){
isRated.rated = true;
isRated.rating = parseInt(ratingRes.items[0].Rating,10);
}
2) added single quotes on lines 124, 130, 136, otherwise image url’s with spaces (e.g. ‘style library’) are not working:
styleBuffer.push(“background-image:url(‘”+argObj.starImageSrc[0]+”‘);”);
Jeroen
Hi,
Thank you for the feedback. I have updated to v2.3 to fix the bugs you pointed out. This will fix the problem where “countOneHitPerUser”, “countOneHitPerUserPerDay” and “oneRatingPerUser” setting was not working.
The errors you experienced using jQuery > 1.8 originated from a deprecated jQuery function: jQuery.browser.
Alexander
I do not get the hits count, i just get -1
This is my configuration
src=”/HitCounter/jquery-1.6.4.js
src=”/HitCounter/spjs-utility.js
src=”/HitCounter/HitCountrAndStarRatingForSharePoint.js
counterListName:’HitCounter’
counterListBaseUrl:’http://owdshp01/’
website url: http://owdshp01/SitePages/Home.aspx
list url http://owdshp01/Lists/HitCounter/AllItems.aspx
Data is going to the list with votes looks right, but has no referringURL
Do votes not work in IE8
Please Help
Hi,
The counterListBaseUrl is wrong. Look at the page source by right clicking > view source. Look for the variable “L_Menu_BaseUrl” – this is the value you want to use.
Alexander
Thank you for the info, but my L_Menu BaseURL=””; has nothing in the quotes area not sure why?
Any thoughts
Thanks
James
Sorry for the late reply, the value is “” and it is this you should use – like this:
Alexander
Hi, I have utilized Alexander’s HitCounter solution on a SharePoint Search Results page and altered it slightly to record a users Search Queries in plain text within the HitCounter List.
If you want to know the details, I’ve added it to my Blog here: http://sharepoint2020.wordpress.com/2013/07/01/record-search-results-queries-to-a-list-using-a-hit-counter/
I’m planning to try this on SP2013 – have you done any testing? Can the ratings be displayed in a list view or can it only be on the item form? I would also like to rate the time from the list view, is this possible?
Hi,
I have not tested it on SP2013. Let me know how it goes. This solution will not work for list views.
Alexander
Hi Alex,
Does the script not work if the ID isnt in the URL?
My URL doesnt contain the ID so it doesnt get the matching post in my discussion board and i end up with the below . . .
urlDir: /sites/Retail/library/SMART/Lists/Test/Flat.aspx?ID=
My current full URL is below from the rendered discussion board.
/sites/Retail/library/SMART/Lists/Test/Flat.aspx?RootFolder=%2fsites%2fRetail%2flibrary%2fSMART%2fLists%2fTest%2f2%20%2d%20easy%20to%20spot&FolderCTID=0x01200200E8086158E19B5C408FE1A81CF0DB285D&TopicsView=http%3A%2F%2Fportal%2Eu%2Ddom1%2Eu%2Dssi%2Enet%2Fsites%2FRetailCustomerService%2FBillinglibrary%2FSMART%2FLists%2Ftest%2FAllItems%2Easpx
Can the ID be obtained from within the post itself as i can see the ID on the post but not via the URL?
Or can this be made to work from the subject line? I know it would reset if the subject was changed but that is something i can put up with.
Cheers
Leon
Hay Alexander,
I’ve got a problem getting your counter to run, hope you can help.
I have inserted the CEWP into a SitePage to try out your counter. I can use the ratings, which are working fine – counting, average, new ratings without any problems. But when it comes to HitCounts, there are no entrys made in the list, so the HitCounter always says “0 Hit”.
I’ve read the code over and over, but got no idea, what to fix.
In case it helps you, here is the debug-output:
Configuration
counterListName:rating
counterListBaseUrl:/sites/CR502/
countHits:true
hitCounterVisible:true
countOneHitPerUser:false
countOneHitPerUserPerDay:false
hitSuffix:Hit,Hits
isDispForm:false
activateRating:true
starImageSrc:/sites/CR502/hitcounter/star_off.gif,/sites/CR502/hitcounter/star_on.gif,/sites/CR502/hitcounter/star_selected.gif
starCount:5
starMouseoverArr:Very poor,Poor,Good,Very good,Fantastic
oneRatingPerUser:false
ratingCountSuffix:Vote,Votes
alreadyRatedMouseover:You have already given this item {starCount} stars!
debug:true
Variables
userId: 66
urlDir: /sites/CR502/SitePages/test.aspx
refURL: https://ecs.telekom.de/sites/CR502/SitePages/Forms/AllPages.aspx
Total hits: 0
Total number of ratings : 2
Rating average : 4
isRated by current user: true
Current user rating: 5
Looking forward to any ideas,
Alexander
You need to turn one of the hit types to true instead of both being false
countOneHitPerUser:false
countOneHitPerUserPerDay:false
Hay leon,
Yeah, thought so, too and tried with countOneHitPerUser:true but still the same problems. Though, might try again tomorrow.
Any other ideas, someone?
Thanks in advance
Alexander
Me again,
tried both now and still not working. There are no entries made in the list “rating” with title “Hit”, only with title “rating” when giving some stars.
Rest of configuration as posted above. Any ideas?
Thanks for your help,
Alexander
Hi,
I did a clean test in a new site with no issues. Are you sure you are using the latest version of spjs-utility.js?
Alexander
Hay,
I’m using 1.171. This is the latest version, isn’t it? Collegue had tried with 1.15 before, but didn’t got it running at all, so I downloaded the 1.171 version…
Kindest regards,
Alexander
Yes, this is the latest version. I’m sorry, but I cannot pinpoint the error. You will have to dig into the script and see if you can locate it.
Could it be that you have multiple solutions in the same page and something is interfering?
Alexander
I used a plain Wiki-Page for testing, so there should nothing be interfering. Also, there are no solutions installed on the Site Collection.
Thanks for your help, anyway. I let you know as soon as I found the error / a solution.
Kindest regards
Alexander
The wiki page may be the cause. I have not tested it in a wiki. Can you send me a description / screenshots of how you have implemented it in the wiki page?
Alexander
Simple as it could be. I followed your instructions and build a customized list with the necessary fields and a library with the js-scripts and the gif-images and – as using SPF2010 – a txt-file for the CEWP. The configuration is as postet in my first message except regularly testing with hitCounterVisible:true, countOneHitPerUser:false, and reversed.
I then added a new Wiki Page to the SitePages-library called “test” and added the CEWP with link to the txt-file.
As I said, rating works fine, but for Hits there are no entries in the “rating”-List, so it always says “0 Hit”.
For what did you have it tested apart from “Blog”? May it work for a customized list item Display-Form?
Thanks again for your help!
Alexander
I tested and it works as it should. We are back to you digging into the script…
Let me know what you find, and yes, you should be able to use this code in any page inheriting from the master page.
Alexander
After realising, that “referringURL” was always empty, I out-commented line 223 of HitCounterAndStarRatingForSharePoint.js, so the refURL is not given to spjs_additem and now it works.
Where is the referringURL needed or is the value necessary at any point or for any feature?
Regards
Alexander
You can safely remove this line as it is only for information purposes. Glad you figured it out!
Alexander
Hi,
I suspect the length of the referring URL is to long for the single line of text field. Try changing this field to multiple lines of text (plain text) and see if this helps (or just comment out the line as you have done).
Alexander
Hi Alex,
Thank you very much for sharing your knowledge with us.
I want to modify a little your script so I will use it for counting Team Discussion Views.
Unfortunatery I realized that in Team Discusion every Discussion URL content a Subject of this Discusion. Can you please help me with modification of your script?
Pawel
I’m not familiar with the team discussion. Is it individual “items”, or a list view you want to count the views on? If possible, send me a screenshot of the page.
Alexander
Hola tengo un problema con el hitCounter y el Ranting en IE8
alguna idea.
Sorry, English only.
Alexander
Hi, I have a problem with the hit Counter and Rating for viewing in IE8.
any ideas?
I need more details about what’s not working.
Alexander
Hi Alexander, the error happens when viewing me ranting in ie8 version 8.0.60001.18372 on page load not present anything, goes blank, and check with debugging and error I have no scripts, I’m working with SP2007. check in version of IE8 8.0.7601.17514 and I have no problem not only happens to users with version 8.0.60001.18372 of ie8.
Any idea?
Hi Alexander, the error happens when viewing me ranting in ie8 version 8.0.60001.18372 on page load not present anything, goes blank, and check with debugging and error I have no scripts, I’m working with SP2007. check in version of IE8 8.0.7601.17514 and I have no problem not only happens to users with version 8.0.60001.18372 of ie8.
Any idea?
Hi,
Sorry, but as long as you do not provide an error message, I have nothing to go with. Could you upgrade to a newer version of the browser?
Alexander
I’ve tested,it’s worked on SP2013 .
I tried to find the solution about hits counter with a long time. Thank you very much.
Hi Alexander,
Love your post. It worked perfectly for me. But what if I have around 500 pages to rate and have some hundred thousand users. I see that when the user rates, the code creates an item in ratings list. This way my ratings list will have 500 multiplied by (some hundred thousand users), which looks scary to me. Do you have any other way to handle this kind of scenario?
Hi,
I agree, it sounds scary… I do not think this solution can be used in your scenario. I do not know of other solutions, but I guess you can find a commercial product that does not store the data in a SharePoint list somewhere out there.
Alexander
Ok, Thanks for the quick reply.
Alex,
Is it possible to display the “Title” of the item being hit?
Field ‘urlDir’ is capturing location path-name and ItemID, however I just want to capture itemID. I tried replacing “location.pathname+”?ID=”+itemID;”
with
“itemID”
but no luck. please indicate where I should be making changes to accommodate above change.
I also like to add an extra column, ‘lookup’, which gets populated based on itemID. lookup will connect hit-counter to parent list. is it possible? what changes do i have to do to achieve this?
Hi,
If you can get the full location.pathname and the itemID, you should be able to use only the itemID by changing the line
to
The lookup column can be added as a single item lookup, and can be populated by adding to the data object in the spjs_addItem function like this:
This will work only for the list that the lookup column is targeting.
Alexander
Hi Alexander,
Following Parth question, can you help us with a easy way to display the “Title” of the item being hit?
It can be stored in a new column for example.
Thanks for your usual help and amazing solutions.
Hi Alex,
I Love your post. It Worked perfectly for me. but what if i have 800 page and have more than 2000 users. it will have an impact to server performance. is it possible to save the average rating in other sharepoint list and RatingStars CEWP get the value from that list?
when the webpart loads it also counts the rating average right?
can we change that if the user rates the contents then it trigger the rating average? so the average is not during the webpart load but only when user rate the content.
thanks
Hi,
You are free to modify it as much as you like, but I’m afraid I cannot do it for you as I’m up to my neck in work.
Alexander
Hi,
As I wrote in the article:
Note: If your pages will have more than a few thousand hits, you most likely would want to hide the “hitcount” from the users. This has to do with the fact that rendering the number of hits in the browser requires the data to be pulled down to the client for counting.
You must test it to see how it performs.
I’m not sure I understand what you mean by storing the average rating in another list.
Alexander
Hi Alexander,
Any update on the question below ?
Following Parth question, can you help us with a easy way to display the “Title” of the item being hit?
It can be stored in a new column for example.
Thanks for your usual help and amazing solutions.
Hi,
Sorry for the late reply. You must add a new field to the configuration list, and update the code here:
Add a new key:value pair here to address the new field, and pass in a variable for the title of your list item – for example like this:
Alexander
Hi,
I’ve tried for several hours no to get this to work. And though it seems simple enough I’m stuck with the “An error occured! Please verify “counterListName” and “counterListBaseUrl”.”-message.
I’ve tried both GUID and display name, I’ve checked the L_menu_baseurl which says “” (I’ve also tried every possible combination other than that to make sure. I’ve recreated the HitCounter list.
I’ve tried jquery version 1.11.0, 1.9.1 and 2.0
I don’t know what else to to..
Any suggestions?
Thank you for a great site btw!
Hi,
Post your CEWP code here – wrap it in <code> tags.
Alexander
Can we have the “like” button and use the one hit per user on the like button? Ideally, each time someone comes to a page, it is a hit, but then hit the like button and it is only the 1 time for that user.
Can this happen? If I try to combine your old solution with your new, swapping out the stars/likes choices, do you suspect there to be much issue? (I am a novice programmer…)
Hi,
I do not think you can mix these without a rewrite. I’m sorry, but I do not have the capacity to do this.
Alexander
Fantastic job Alexander, thank you for sharing. It works perfectly well on SP2010.
Please help Alexander.
I downloaded
– HitCounterAndStarRatingForSharePoint.js and images.
– jquery-1.11.1.min.js from here http://jquery.com/download/
– spjs-utility
I made changes in the CEWP code. That is, updated the src, javascript version reference, counterListBaseUrl, and counterListName.
I created the CEWP on the same site where I created HitCounter list (with columns same as in the snapshot).
Now, I do not know how to proceed further.
I have a list with 200 items, say list name is, Products. I want the hit count for each item in that list. How can I give reference of my “Product” list to the CEWP code or the scripts? I have no clue how to proceed further. Please explain.
Hi,
The CEWP must be added to the page you want to count the hits for – like the DispForm for your “Products” list.
If nothing show when you add the CEWP, try bringing up the developer console (F12 > Console) and look for error messages.
Alexander
Hi Alexander,
It is working like magic! Thanks ton. =)
Is there a way to show hit counts next to each item?
Also, I do not wish to record browser info, so commenting all browser info related code in HitCounterAndStarRatingForSharepoint.js will do the trick?
Hi,
Unfortunately there is no method for showing this in the list view. This is because the query would be to “heavy” if you should pull back all records for all items in the view.
You can comment out the part of the code for the browser info.
Alexander
Hi,
Thanks for the script!
I am new to sharepoint and and i have one basic question…
When i add new content or script editor web part to the blog and insert the code the counter works well. But i want to have counter in each blog post. I already tried inserting code in post.aspx (via sp designer) but no luck. Where should this code be inserted and how? Thanks!
Regards
You must add it to the page where you want the rating to appear. Edit the page as described here: https://spjsblog.com/general-tips/
Alexander
Hi,
Thank you! _Everything works ok now, but the filed/column “user” is empty in my list. All other fields are filling well. Any idea?
Hi,
Sorry for the late reply. I guess this has to do with the script using the variable “_spUserId” which is not present in SP2013. Open the file “HitCounterAndStarRatingForSharePoint.js” and search and replace “_spUserId” with “_spPageContextInfo.userId”.
Alexander
Great! Now it works like a charm. Thanks!
Hi Alex,
Some amazing scripts you have developed, thank you so much! I’m working my way through a few of them.
I’m having a specific issue with the debug error message and a slight change to your code which would allow me to capture either the full url (location.href) or append the url parameters to the existing location.pathname to give me the same detail. (location.pathname+location.search).
I’ve used the console to determine that these are both valid – and the resultant string returned is shown correctly.
In both cases the “hit” with all relevant info is created in the SharePoint list, including the expected URL value and all other fields. However the big yellow debug error message is then displayed complaining of incorrect counterlistname and counterlist base url. Obviously they are correct because the hit is recorded.
It looks like an issue with hitRes:
hitRes = spjs_QueryItems({listName:argObj.counterListName,listBaseUrl:argObj.counterListBaseUrl,query:queryBuffer.join(”),viewFields:[‘ID’],rowLimit:1});
if(hitRes.count===-1){
argObj.debug=true;
errorMsg = “An error occured!\nPlease verify \”counterListName\” and \”counterListBaseUrl\”.”;
but unfortunately I’m not bright enough to work out how to resolve. Are you able to help at all?
The url parameter is in the form ?action=ViewTopics&fid=4&forum=Testing-Forum so I’m guessing that some of the characters there may be causing the problem? Is there a way to re-evaluate or bypass this check? I would purely like to capture hits on the page (with querystring), I don’t need any other functionality.
Thanks
Adam
Hi,
Add the function call with the arguments and I’ll see if there are any errors there.
Alexander
Hi Alex,
Really fast response thank you.
I’m pretty new to javascript so please excuse any misunderstanding of what youre asking.
In version 2.3 of your hitcounterandstarratingforsharepoint.js script, there is one line that sets urlDir to location.pathname (I’m not using isDispform, set to false in the parameters file). This works perfectly.
I have tried two variations (both of which correctly add the url into the item in the hitcounter list but then return the debug message for counterlistname and counterbaseurl):
Changed location.pathname; to location.href;
Changed location.pathname; to location.pathname+location.search;
Everything else in the script is unchanged version 2.3.
I have seen the same behaviour with the unmodified script when the number of items in the hitcounter list exceeds the list view threshold (set at 10, 000 items). There were 10, 050 items in the list when I spotted the debug message was appearing…my fix was to reduce the size of the list to get around that, but now I’m thinking there may be a better way.
Modified code;
// Is it used in DispForm and needs to separate the items by ID?
if(argObj.isDispForm){
itemID = GetUrlKeyValue(‘ID’);
urlDir = location.pathname+”?ID=”+itemID;
}else{
urlDir = location.pathname+location.search;
}
Hi,
I’m afraid you may have found the cause of the error in the number of items in the list. I guess the only way to be able to use this with this much list items is to disable the “hitcount” from the view by setting “hitCounterVisible” to false. This way you can log the hits, but cannot display the hitcount to the end user.
Let me know if this helps,
Alexander
Hi Alex
Thanks for bearing with me, I’m afraid I may have confused you with too much info.
The issue I’m having with trying to capture the url parameters occurs even in a virtually empty list, the hits are recorded but the debug error is shown at the top of the page (even with debug:false set).
Exceeding the 10,000 list items also causes the same debug error, but again, hits are still recorded in the list.
I’m not displaying the number of hits to the end user in either case – in the parameters file I have:
hitCounterVisible:false,
The problem seems to be with the code:
hitRes = spjs_QueryItems({listName:argObj.counterListName,listBaseUrl:argObj.counterListBaseUrl,query:queryBuffer.join(”),viewFields:[‘ID’],rowLimit:1});
if(hitRes.count===-1){
argObj.debug=true;
errorMsg = “An error occured!\nPlease verify \”counterListName\” and \”counterListBaseUrl\”.”;
}else if(hitRes.count===1){
isHit = true;
}
Could you explain what this check is for – can it simply be removed? I’m not sure we need to query the list if we’re just recording items?
Adam
Sorry for the delay. This is a check to see if the user has already visited this list. This check may fail if the itemcount in the list exceeds the list view threshold (default 5000 items).
I’m not sure what the problems you experience are caused by, and without looking at your site “hands on” Its hard to tell.
Alexander
Great solution. Installed and started running perfectly in a very short time. Only issue is, the “one hit per user” doesn’t work. I want the page to let users give stars just one time ever. Am working with your most recent version of all the files and am sure I have the params set correctly:
countHits:true,
hitCounterVisible:true,
countOneHitPerUser:true,
countOneHitPerUserPerDay:false,
hitSuffix:[‘Hit’,’Hits’], isDispForm:true,
activateRating:true,
But, I find a user can go back to the same page, and gives stars over and over again. Not only on each additional visit, but even in the same visit. Additionally, they get no popup telling them they’ve already voted (which I guess they wouldn’t since it’s letting them vote over and over anyway).
I’m on MOSS SP 2007.
Appreciate any help or thoughts on this.
Any errors in the developer console (hit F12 > Console)?
Alexander
Hi Chris,
I found that the solution doesn’t work for environment that is upgraded from SP 2010 to SP 2013 but still running in SP 2010 compatibility mode.
Basically it doesn’t take user id and grabs all other details but user is always blank.
I was able to fix it. In SP 2013 (even though running in compatibility mode), the _spUserId is now _spPageContextInfo.userId.
I have installed your code in SP2013 and the Hit Count is working well – too well. Regardless of changing the setting for countOneHitPerUser or countOneHitPerUserPerDay the hit count continues to go up. In this case, that is problematic as the code has been placed on a landing page and would expect Users to go back multiple times and only want to track once per day. Any thoughts?
Hi,
I have not tested this in SP2013. Do you get any errors in the developer console in IE? (hit F12 > Console).
Alexander
I do not. However, it the once per day setting is based off of the Username, that may be the issue. I do not have User Profile Services established. Is there a way to base the once per day off of the created by field or modified field?
Ah – I forgot – the problem is the user ID that is not in the same variable in SP2013.
Open the script and search / replace
with
This should do the trick.
Alexander
Hi, Alexander.
Thanks for this helpful article. I implemented it for one of my SharePoint site pages and it worked perfectly. But I had a requirement to implement view counter for each discussion thread. How many people view each thread? Is there a way to implement the way you do this one (page view counter)?
Thank you!
Sorry, but I cannot help you with this request. You are however free to modify the code to fit your requirements.
Alexander
Something odd… When editing the page the counter shows and the list gets updated. But in normal view the page does not show the counter and the list gets not updated….
Sorry for the late reply. Have you hidden the CEWP (in the edit web part tool pane)? – this would explain this behavior.
Alexander
Don’t worry: five days is no delay for free support 😉
That’s not the issue I am afraid, the web part is not hidden…
It is hard to tell what could be the issue. Do you see any errors in the developer console (hit F12 > Console)?
Alexander
I am able to see the hit counter and star ratings and the corresponding HitCounter list is tracking user hits, which is excellent.
Though when I have “countOneHitPerUser” set to true, it is still incrementing the counter if the same user reloads the page. When I examine the HitCounter list, the “User” field is empty for each item – I’m assuming this is the reason why it is not recognizing when a user hits the page more than once.
Any ideas what the issue could be? I am using this with SharePoint 2013. Thanks!
Hi,
You must replace a variable in the script to make it work in SP 2013 – you find this in a few comments above: like this one
Alexander
Hi Alex,
I think I am soooo close to getting this to work, but the hit counter is not incrementing. I am running a SP2013 environment and have replaced the _spUserId – no luck. The HitCounter list is set-up and it logs everything correctly when I rate the page.
Any suggestions would be appreciated.
Here is my debug dump:
Configuration
counterListName:HitCounter
counterListBaseUrl:/teams/analyticscommunity/
countHits:true
hitCounterVisible:true
countOneHitPerUser:false
countOneHitPerUserPerDay:true
hitSuffix:Hit,Hits
isDispForm:true
activateRating:true
starImageSrc:/teams/analyticscommunity/siteassets/star_off.gif,/teams/analyticscommunity/siteassets/star_on.gif,/teams/analyticscommunity/siteassets/star_selected.gif
starCount:5
starMouseoverArr:Very poor,Poor,Good,Very good,Fantastic
oneRatingPerUser:false
ratingCountSuffix:Vote,Votes
alreadyRatedMouseover:You have already given this item {starCount} stars!
debug:true
Variables
userId: 286
urlDir: /teams/analyticscommunity/SitePages/Actionable%20Analytics%20CoE.aspx?ID=
refURL: https://ent301.sharepoint.hp.com/teams/analyticscommunity/_layouts/15/start.aspx
Total hits: 0
Total number of ratings : 4
Rating average : 3
isRated by current user: true
Current user rating: 4
Not sure what this could be, but it MAY have to do with the “minimal download strategy”. Please disable this site feature and see if it helps.
Do you see any errors in the developer console (hit F12 > Console)?
Alexander
Sorry no errors on Developer Console. I will try to disable – Thank you.
I am using SP 2013 and I am getting a property ‘match’ of undefined or null reference error in the console log in spjs-untility for line 408:
r = xhr.responseText.match(/]*>(.*)/i);
Not sure why it errors out here, but the line of code failing is used to write out the error in the query. Try opening the developer console (hit F12) and going to the “Network” tab. Look for errors from “lists.asmx” – double click and click into the “Response body” tab. Do you see any error messages there?
Alexander
Thought I’d share in-case anyone else having this issue.
The Issue I had was that on some IE8 browsers, the Hit count & rating wouldn’t work but when accessing from a Chrome browser on the same machine would work perfectly.
What confused me was that on other Machines running also IE8 but slightly newer build it would also work fine… (I work in a company where we have plenty of variations between browsers).
After some debugging I found that the root cause was due to in some cases (fro some browsers) the “BROWSER” string would exceed 256 chars. Where in SP the “Browser” column was defined as Single line of text.
So once I changed it to Multiple lines of text (Plain text), every thing started work great!
Really thanks for a great script! I would suggest to update the instructions for all “Single line of text” columns to “Multiple lines of text (Plain text)” – or at list the Browser column…
Thanks again!