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