Monday, July 1, 2013

SharePoint - Get list items with javascript

There are many ways of fetching list items of a SharePoint list. The best way to do this is by using c# code, but it is also possible to do it by using javascript, i.e. using jQuery library called SPServices.

NOTE: This post describes code that is used in older versions of SharePoint. If you are using SharePoint 2013, then check out this post.

SPServices is a jQuery library that uses SharePoint web services and it is extremely easy to use. I would always advise to use c# code, but, if you're working on a small scale project that has no need for complex developer solutions, this is a quick and fast fix. You can just add it to your aspx page in SharePoint Designer.

This is the code (this example is taken from Codeplex):

<script type="text/javascript" src="filelink/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="filelink/jquery.SPServices-0.6.2.min.js"></script>
<script language="javascript" type="text/javascript">

function GetAllItems() {
  $().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "Announcements",
    CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {
        var liHtml = "<li>" + $(this).attr("ows_Title") + "</li>";
        $("#tasksUL").append(liHtml);
      });
    }
  });
}
</script>
<ul id="tasksUL"/>


This example will return all items from SharePoint list "Announcements", but, you can restrict the number of rows that it will return, select desired fields that you wish to return or sort them as you wish by modifying CAML query in in this function.

7 comments:

  1. wow its cool but its working or not ?

    ReplyDelete
  2. Gok, this is an old post, it is for SP2010. If you are using SP 2013, there are different solutions, like REST web services or JSOM.
    REST:
    https://msdn.microsoft.com/en-us/library/office/fp142380.aspx
    JSOM:
    https://msdn.microsoft.com/en-us/library/office/jj163201.aspx

    ReplyDelete
  3. can you give me code for Getting list Items form List using Sp services or REST in script editor

    ReplyDelete
    Replies
    1. gok,
      I wrote a new post on this topic:
      http://sharepoint1on1.blogspot.com/2015/06/sharepoint-2013-get-list-items-with.html
      Enjoy!

      Delete