Monday, June 22, 2015

SharePoint 2013 - Get list items with javascript

In one of my older posts (here), I demonstrated how to fetch items of a SharePoint list with javascript using SPServices. In SharePoint 2013, we are no longer using SPServices. Now we have two different approaches; JSOM (JavaScript Object Model) and REST (OData) services. 

Now, I will not describe in details how each of them works, I will just show you the code for getting list items in each technology. If you want to know more details about these technologies and differences between then, check this post on Andrew Connell's blog:
http://www.andrewconnell.com/blog/sharepoint-2013-csom-vs.-rest-...-my-preference-and-why

Example code for both REST and JSOM:

REST:



function GetListItemsFromSPList() {
    var siteUrl = _spPageContextInfo.webAbsoluteUrl;

    $.ajax({
        url: siteUrl + "/_api/web/lists/getbytitle('My List Title')/items",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            // Returning the results
            var listItems = data.d.results;
            listItems.forEach(function (entry) { 
               // Do something with list item which is in 'entry' object              
            });
        },
        error: function (data) {
            alert("Error: " + data)
        }
    });
}
 


Explanation: First, we are getting the URL of our site in through object that resides in every SP page (_spPageContextInfo). Then, we making ajax call to REST APIto get list item of a SP list (you need to put your list's name instead 'My List Title'). If call was successful, then list items will be returned in object 'data.d.results' and we can access them in forEach loop.


JSOM:



function GetListItemsFromSPList(listId) {   
    // here we are fetching current context, but you can also use explicit call (where 'site'  is URL of your site):  var clientContext = new SP.ClientContext(site);
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getById(listId);
    var query = SP.CamlQuery.createAllItemsQuery();
    var allItems = list.getItems(query);
    context.load(allItems, 'Include(Title, Id)');
    context.executeQueryAsync(Function.createDelegate(this, function () { onQuerySuccess(allItems); }),
        Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySuccess(allItems) {
    var ListEnumerator = allItems.getEnumerator();
    while (ListEnumerator.moveNext()) {
        var currentItem = ListEnumerator.get_current();
        // do something with your list item

    }
}
function onQueryFailed(sender, args) {
    alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
}
 


Explanation: In method 'GetListItemsFromSPList' we are getting the current context, getting the SP list by its id (it is also possible to get list by title) and we are making query to get all items from that list ('SP.CamlQuery.createAllItemsQuery()'). After that, we need to explicitly include which fields of our list items we are going to use. For example, I included 'Title' and 'Id' field (context.load(allItems, 'Include(Title, Id)')). After that, we are making async call to SP list (context.executeQueryAsync). If query was successful, than method 'onQuerySuccess' will be called. In this method, we can now iterate through our list items and do want we want with them. If query was not successful, method 'onQueryFailed' will be called.

14 comments:

  1. Great article… Thanks for your great information, the contents are quiet interesting. I will be waiting for your next post.
    SharePoint 2013 Training"

    ReplyDelete
  2. How do I filter what items come back? Say I only want items that are of a specific content type?

    ReplyDelete
    Replies
    1. When using REST, filtering is done by adding $filter at the end of the URL:
      "/_api/web/lists/getbytitle('My List Title')/items$filter=Title eq 'my title'
      This would filter all items in your list that have title equal to string "my title". I am not sure how it works with content type names, but I am sure that it works with Content Type ID like this:
      "/_api/web/lists/getbytitle('My List Title')/items?$filter=startswith(ContentTypeId,'0x0120')"
      So, this will filter all items whose ContentTypeId starts with 0x120, and that ID are folders.

      Delete
  3. I'd always use JSOM(CSOM) since it is a lot faster.

    ReplyDelete
  4. what if you just want to access one list item only, must yo use the enumerator?

    ReplyDelete
    Replies
    1. No, you don't. But, then you don't use
      var query = SP.CamlQuery.createAllItemsQuery();
      You just get the single item by its ID.

      Delete
  5. But can anyone tell where to use this script...content editor or sharepoint designer

    ReplyDelete
    Replies
    1. You can add it to your page through Sharepoint GUI - if you created new page, you can add new content editor web part (or script web part) and copy-paste the code.
      You can open SharePoint Designer and open NewForm (or EditForm) and add this code there.
      You can create project in Visual Studio and create new script there, create pages, web parts or whatever and include this code there.
      There are many ways...

      Delete
    2. Where shall we put the jsom code if we are using an html page? How to specify the url in the client context. Please help really urgent

      Delete
  6. while running the code /_api/web/lists/getbytitle('My List Title')/items?$top =250";
    I am getting only default list items(100). How can i show all teh list items.

    ReplyDelete
  7. This comment has been removed by a blog administrator.

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Hii I just wanted to retrieve the data from first column on selecting the list row . How do I do that

    ReplyDelete