Hit counter and star rating for SharePoint

Change log
June 06. 2013
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:
IMG

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:
IMG


Step 2:
Download the code for the file “HitCounterAndStarRatingForSharePoint.js” and the images star_off.gifstar_on.gifstar_selected.gif 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.

Copyright and disclaimer

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…


161 thoughts on “Hit counter and star rating for SharePoint”

  1. 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?

    1. 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

  2. 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”

  3. 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???

    1. 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.

  4. 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… 🙁

    1. 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.

  5. 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.

  6. 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.

    1. 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!

  7. 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.

    1. 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

  8. 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/’

    1. 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.

    2. 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

  9. 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?

  10. 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

  11. 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

    1. 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

    2. 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

  12. 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.

  13. 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.

  14. 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

  15. 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);

    1. 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.

  16. 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’]});

    1. 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

  17. 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

    1. 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

  18. 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

  19. 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.

  20. 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

  21. 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

    1. 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.

  22. 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:

    1. 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

  23. 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.

  24. 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?

    1. 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

  25. 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

  26. 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

  27. 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

    1. 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

  28. 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

      1. Thank you for the info, but my L_Menu BaseURL=””; has nothing in the quotes area not sure why?

        Any thoughts

        Thanks
        James

  29. 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?

  30. 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

  31. 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

      1. 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

      2. 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

  32. 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

    1. 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

      1. 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

      2. 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

      3. 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

      4. 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

      5. 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

      6. 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

  33. 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

      1. 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?

  34. 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?

  35. 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?

    1. 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

  36. 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?

    1. 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

      urlDir = location.pathname+"?ID="+itemID;

      to

      urlDir = itemID;

      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:

      data:{'Title':'Hit',
      URL:urlDir,
      User:userId,
      ReferringURL:refURL,
      Browser:browserInfo,
      YourLookupColumn:itemID}

      This will work only for the list that the lookup column is targeting.

      Alexander

  37. 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.

  38. 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?

    1. 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

    2. 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

  39. 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.

    1. Hi,
      Sorry for the late reply. You must add a new field to the configuration list, and update the code here:

      hitCountRes = spjs_addItem({listName:argObj.counterListName, listBaseUrl:argObj.counterListBaseUrl,
      		data:{'Title':'Hit',
      		URL:urlDir,
      		User:userId,
      		ReferringURL:refURL,
      		Browser:browserInfo}});

      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:

      // Find list item title in dispform if the Title field is the topmost field in the form
      var myTitleValue = $("table.ms-formtable:first").find("td.ms-formbody:first").text();
      
      hitCountRes = spjs_addItem({listName:argObj.counterListName, listBaseUrl:argObj.counterListBaseUrl,
      		data:{'Title':'Hit',
      		newFiell:myTitleValue,
      		URL:urlDir,
      		User:userId,
      		ReferringURL:refURL,
      		Browser:browserInfo}});

      Alexander

  40. 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!

  41. 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…)

  42. 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.

    1. 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

      1. 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?

      2. 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

  43. 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

    1. 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

  44. 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

      1. 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.

  45. 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;
    }

    1. 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

      1. 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

      2. 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

  46. 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.

  47. 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.

  48. 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?

      1. 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?

      2. Ah – I forgot – the problem is the user ID that is not in the same variable in SP2013.

        Open the script and search / replace

        _spUserId

        with

         _spPageContextInfo.userId

        This should do the trick.

        Alexander

  49. 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!

  50. 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!

  51. 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

    1. 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

  52. 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);

    1. 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

  53. 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!

Leave a Reply