Get Recently added items in SharePoint and Office 365 using J query and Rest

Recently added or Trending is a new feature which has been so common in most of the web applications.  Though it was started by the social media engagement  now it has been accepted by most of the major industries and you can see that in most of the web sites of any organization.

In  this article we will learn how to get  the most recent items added in a SharePoint site collection using Rest and Jquery from the client side. We will use the search rest api available to get the most recent items in a site collection and display them.

This application relies on the search server and it’s crawling schedule. In SharePoint online it is very quick, i get most of the items in search result with in an hour. But in on-premise servers it depends how your search server is setup to display any item in the search.

Rest api’s Used and Details

  • $.ajax({ url: “siteurl/_api/search/query?querytext=’Path:siteurl+ContentClass:STS_ListItem+ContentClass:STS_ListItem_DocumentLibrary’&trimduplicates=true &rowlimit=10&sortlist=’created:descending'”,
    type: “GET”,
    headers: {
    “Accept”: “application/json;odata=verbose”
    },
    success: function(data) {} });
  • Replace the siteurl in two place with your site collection URL.
  • Breaking the querytext
    • Path:siteurl+ContentClass:STS_ListItem+ContentClass:STS_ListItem_DocumentLibrary’&trimduplicates=true &rowlimit=10&sortlist=’created:descending'”
      • siteurl–> sitecollection URL where you are going to search
      • ContentClass:STS_ListItem–> all the list items inside the site collection
      • ContentClass:STS_ListItem_DocumentLibrary –>all the documents inside the site collections
      • trimduplicates=true –> remove the duplicates
      • rowlimit=10 –> display only 10 rows in result you can increase the row limit according to your requirement
      • sortlist=’created:descending’–> sorting the items by it’s created date so the last created comes first

So we use a rest api to send a search request in the particular site collection and once we get the j son in return. we analyze the json and pick the part from the json that is relevant to our search results.

let us get the json result example from the search

1
J Son Data received from the search request made

So from the image above we need couple of things to build our result items.

  • Item Title–> which is the third item key Title in the array of item results ; results[3].Value
  • Item Link–>  which is the sixth item key Path  in the results array; results[6].Value.
  • Finally the parent list name and URL.
    • This is bit confusing between SharePoint online and SharePoint 2013.
      • In SharePoint 2013 it is the item index 19 from the result
      • In SharePoint online it is the item index 20 from the result
      • This item has the ParentLink key which holds the parent list or library value.
        • we use the ParentLink and parse it so that we get the list name from the link which is the URL of the list( i tried to get the real title of the list but was not able, if you know how to please let me know)

Now after understanding all these aspects let’s take a look at the codes.

Source Code


<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MostRecentItems</title>
				<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>

<script type="text/javascript">
$(document).ready(function () {

 $.ajax({
 url: "https://theinventor.sharepoint.com/_api/search/query?querytext='Path:https://theinventor.sharepoint.com+ContentClass:STS_ListItem+ContentClass:STS_ListItem_DocumentLibrary'&trimduplicates=true &rowlimit=10&sortlist='created:descending'", // ur site url goes here
 type: "GET",
 headers: {
 "Accept": "application/json;odata=verbose"
 },
 success: function(data) {
 //log the json to analyze and visualize
 console.log(data);
 var items=data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
 //log the actual 10 items that is going to be displayed
 console.log(items);
 $.each(items, function(index, item) {
 var ret= items[index].Cells.results[6].Value;
 //replacing any spaces in the URL
 var hell= ret.replace(/ /g,"%20");
 var listurl= items[index].Cells.results[20].Value;
 //replcaing any spaces in the URL
 var listurla= listurl.replace(/ /g,"%20");
 //Parse the link to get the parent list or library name. The links will be different depending upon lists,library or folders
 if((listurla.indexOf('/Lists') != -1))
 {
 var listname= listurl.split('Lists/');
 var listname= listname[1].substr(0, listname[1].indexOf('/'));
 $('#recent').append('


<div class=recentitems><a target="_blank" class=itemtitle href='+hell+'>'+items[index].Cells.results[3].Value+'</a>: <b><a target="_blank" class=listitle href='+listurla+'>'+listname+'</a></b></div>


');

 }
 else if((listurla.indexOf('/Forms') != -1))
 {
 var listname= listurl.split('Forms/');
 var listnamea= listname[0].substring(0,listname[0].length - 1);
 var alistnamea= listnamea.substr(listnamea.lastIndexOf('/')+1);
 $('#recent').append('


<div class=recentitems><a target="_blank" class=itemtitle href='+hell+'>'+items[index].Cells.results[3].Value+'</a>: <b><a target="_blank" class=listitle href='+listurla+'>'+alistnamea+'</a></b></div>


');

 }
 else{
 var listname= listurla.substring(listurla.lastIndexOf('/') + 1);
 listname= listname.replace(/%20/g, " ");
 $('#recent').append('


<div class=recentitems><a target="_blank" class=itemtitle href='+hell+'>'+items[index].Cells.results[3].Value+'</a>: <b><a target="_blank" class=listitle href='+listurla+'>'+listname+'</a></b></div>


');

 }

 });

}
 });

 });

</script>

</head>

<body>
<div id="recent"></div>
</body>

</html>

Puts this code in a html page and upload that to a SharePoint document library.

Add a web part page

Edit the page

Add content editor web part

In the web part properties panel add the link to the HTML file and save the page

Once your page loads then it will display the most recently added 10 items in the SharePoint site collection.

a
Most Recent Items

So above is the result of the most recent items in my site collection. the left hand side is the items title with link and the right hand side is the parent list/libraries with link.

You can add css and make it look more attractive as per your need. This web part can be placed anywhere in  a page or homepage with title like recently added.

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s