0

I have created a page and now I want to get the track of hit count of that page. I want to store that no. in a sharepoint list.

On every page load the count should get increased by 1 and get stored in a sharepoint list.

Please suggest only out of the box approach or javascript or jquery code.

1
  • There are native capabilities of tracking and statistic. What's missing in the native feature ? The stats are basics, but your description seems to fit
    – Steve B
    Apr 15, 2019 at 15:04

3 Answers 3

1

This is easily done by creating a custom list with a 1 number column to store the value. Create an element in this list with 0 as value. Then create a script that gets and increments this value through the REST API for lists, and the saves the new value in the list. Add this script in a Script Editor Web Part.

1
  • Thanks Jan for you reply. I am new to sharepoint therefore I am not able to understand how to increase value through the REST API using script. Please explain. Dec 3, 2014 at 5:57
1
<script language="javascript" type="text/javascript">
$(document).ready(function() 
{
    console.log('Enterned');
    retriveListItem();
});

 function retriveListItem()  
{  
    var currentDate=new Date();
    var today=new Date(currentDate.getFullYear(),currentDate.getMonth(),currentDate.getDate());
    var spUrl =_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('HitCount')/items?$select=ID,Count,CurrentDate&$filter=CurrentDate eq '"+today.toISOString().substring(0,10)+"'";

    $.ajax  
    ({  

        url: encodeURI(spUrl),
        type: "GET",        
        headers: {"Accept": "application/json;odata=verbose"},
        cache: false,  
        success: function(data)   
        {  

           if(data.d.results.length >0)
            {
            for (var i = 0; i < data.d.results.length; i++)   
            {  
                var item = data.d.results[i];  
                updateListItem(item.ID,item.Count +1);

            }
            }
            else{
                 var ListDate =(CurrentDate.getMonth() + 1) + '/' + CurrentDate.getDate() + '/' + CurrentDate.getFullYear()
                AddListItem(ListDate,1);
            }

        },  
        error: function(data)  
        {  

            console.log('Request failed. ' + data.responseJSON.error);
        }  
    }); 
}

 function AddListItem(DateField,CountInc)  
{ 
var data = {
            __metadata: { 'type': 'SP.Data.HitCountListItem' },
           CurrentDate:DateField,
           Count:CountInc
      };

        $.ajax({
                    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('HitCount')/items",
                   method: "POST",
                                 data: JSON.stringify(data),
                   headers: {
                       "Accept": "application/json;odata=verbose",  
                        "Content-Type": "application/json;odata=verbose",  
                        "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
                        "X-HTTP-Method": "POST" 

                   },
        success: function(data)  
        {  
            console.log("Record Inserted Sucessfully");
        },  
        error: function(data)  
        {  
        console.log('Request failed. ' + data.responseJSON.error);
        }  
    });  


}

function updateListItem(ID,CountInc)  
{  

    $.ajax  
    ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('HitCount')/items("+ID+")",
         type: "POST",  
        data: JSON.stringify  
        ({  
            __metadata:  
            {  
                type: "SP.Data.HitCountListItem"  
            },  
            Count: CountInc  
        }),  
        headers:  
        {  
            "Accept": "application/json;odata=verbose",  
            "Content-Type": "application/json;odata=verbose",  
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
            "IF-MATCH": "*",  
            "X-HTTP-Method": "MERGE"  
        },  
        success: function(data, status, xhr)  
        {  
            //retriveListItem();
              console.log("Updated the Record");

        },  
        error: function(xhr, status, error)  
        {  
            console.log(data.responseJSON.error);  
        }  
    });
}   

</script>
0
/* Hit counter for SharePoint for the way "Jan Maximilian W. Kristiansen" explained above
 * ---------------------------------------------
 * Created by Manmohan Tomar
 * List Name: HitCounter with Title, URL, Counter, Time & User columns
 * This will create a new list item each time for different pages/urls
 * If new items are not required then update the list not add item each time
*/


/* Call this below function hitCounter() in doc ready */

function hitCounter(){

var LoggedInName;
var URLLink = window.location.href.toLowerCase();

getLoggedInUser().done(function(LoggedInNameTemp){
      LoggedInName = LoggedInNameTemp;



checkCounterVal(function(retCntrVal) {  

    var clientContext = new SP.ClientContext.get_current(); 
    var oList = clientContext.get_web().get_lists().getByTitle('HitCounter');       

    var itemCreateInfo = new SP.ListItemCreationInformation();
    var oListItem = oList.addItem(itemCreateInfo); 
    oListItem.set_item('Title', "PageVisited");
    oListItem.set_item('URL', URLLink);
    oListItem.set_item('Counter', retCntrVal+1);
    oListItem.set_item('Time', new Date($.now()));
    oListItem.set_item('User', LoggedInName); 

    oListItem.update();
    clientContext.load(oListItem,'Include(Title, URL, Counter, Time, User)');

    clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));



}); //checkCounterVal closed



}).fail(function(error){
      alert(error.get_message());
    });  //getLoggedInUser closed



}

function onQuerySucceeded() {

alert("Page visit value increased by 1");

}

function onQueryFailed(sender, args) {

alert('Request failed to save page visit counter: ' + args.get_message() + ' \n and \n ' + args.get_stackTrace());

}


function getLoggedInUser(listTitle,propertiesToInclude)
{ 
   var clientContext = new SP.ClientContext.get_current();
    currentUser = clientContext.get_web().get_currentUser();    
    clientContext.load(currentUser);
    //clientContext.executeQueryAsync(Function.createDelegate(this,onRetUsrQuerySucceeded), Function.createDelegate(this,onRetUsrQueryFailed));
    var d = $.Deferred();
    clientContext.executeQueryAsync(function() {
    var result = currentUser.get_title();
       d.resolve(result);
   },
   function(sender,args){
       d.reject(args);
   });
   return d.promise();
} 


function checkCounterVal(callback) {

var retVarNm = 0;      

    $.ajax({
        url: "https://Your_Site/_api/web/lists/getbytitle('HitCounter')/Items?$select=Counter&$top=1&$orderby=Created desc",
        method: "GET",
        cache: false,
        headers: { "accept": "application/json;odata=verbose" },
        success: function (data) {  

            for (var i = 0; i < data.d.results.length; i++) { 

            if(data.d.results[i].Counter != null) {                       
                        retVarNm = data.d.results[i].Counter; 
                $("#pageVisitCount").text("Page Hit: " + retVarNm);
            }           

                      } 

            callback(retVarNm);  

        },
        error: function (data) {
            alert("Failed to check counter");           
        }
         });//ajax closed

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.