Thursday, August 7, 2014

Reading a SharePoint List using JavaScript Object Model

Using JavaScript is the buzz since the introduction of the SharePoint apps. The JavaScript client side API has improved quite a lot in SharePoint 2013 and this is the only option if you are developing a SharePoint hosted app. When comparing with the server-side object model, I did not found many conceptual differences in the API. If we are to access a list, what we need to do is refer the current site through the current context and then refer the list available in the current site. 

Here is the div tag available in my Default.aspx file which contains an unordered list inside. Forget about the other items later. Will discuss about it in next post.


<div>
<ul id="ToDoItems"></ul>
</div>


Here are some important objects created in the JavaScript API and look how similar they are with the Server-side object model.


//Creates a client context object
var context = SP.ClientContext.get_current();
// Refer the current site through the accessing client context
var web = context.get_web();
//Gets the currently logged in user to the current site
var user = web.get_currentUser();
//Gets all the lists available in the site
var lists = web.get_lists();
// defined for setting the list items later 
var itemCollection;

Now lets see how to pick a single list from the available all lists. 

function loadToDoItems() {

// Gets the list by title
var toDoItemList = lists.getByTitle("ToDoList");

// Check whether list exists or accessible to current user
if (toDoItemList !== null) {
        // Create a CAML query object here. Since we do not need any filtering, go with the empty constructor
var camlQuery = new SP.CamlQuery();
        // assign all the queried list items to a collection
itemCollection = toDoItemList.getItems(camlQuery);
context.load(itemCollection);
        // Actual querying happens here. API connects to the server and request data asynchronously.
        // Here I have defined a function to be called on success and another to be called if fail
context.executeQueryAsync(loadToDoItemsSuccess, loadToDoItemsFail);
}

}

Here goes the success function.

function loadToDoItemsSuccess() {
        // Creates an enumerator from the item collection available
var listItemEnumerator = itemCollection.getEnumerator();
       // Here is an unordered list that I have created in the UI
var toDoUnorderedList = document.getElementById('ToDoItems');

       // Clears if there are any unordered list items available in the unordered list (HTML list)
if (toDoUnorderedList.hasChildNodes()) {
while (toDoUnorderedList.childNodes.length >= 1) {
toDoUnorderedList.removeChild(toDoUnorderedList.firstChild);
}
}

        // This will loop through the list items available in the collection
while (listItemEnumerator.moveNext()) {
                // Gets the current list item
var oListItem = listItemEnumerator.get_current();
                // Select the title field value of the list item. Needed field name should be mentioned here.
var title = oListItem.get_item('Title');
               // Adds a new HTML Unordered list item to the list
var liItem = document.createElement('li');
               // Set the list item title
liItem.innerHTML = title;
               // Append to the list
toDoUnorderedList.appendChild(liItem);
}
}

My fail function will simply give an alert with the error message and stack trace

function loadToDoItemsFail(sender, args) {
alert('Loading To Do Items failed: \n' + args.get_message() + '\n' + args.get_stackTrace());
}

So at the end my list items will be printed like this.


8 comments:

  1. Hello Guru, what entice you to post an article. This article was extremely interesting, especially since I was searching for thoughts on this subject last Thursday. new york web designs

    ReplyDelete
  2. Keep in touch whilst functioning from your own home office with out all of the hassle of purchasing or procurment costly office equipment. Debtors are allowed to apply with their a bad credit score background whenever. nyc web designer

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

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

    ReplyDelete
  5. As I web-site possessor I believe the content matter here is rattling wonderful , appreciate it for your efforts. You should keep it up forever! Best of luck. san francisco brand agency

    ReplyDelete
  6. Admiring the time and effort you put into your website and in depth information you offer. It’s good to come across a blog every once in a while that isn’t the same out of date rehashed material. Great read! I’ve saved your site and I’m including your RSS feeds to my Google account. ux san francisco

    ReplyDelete
  7. This is getting a bit more subjective, but I much prefer the Zune Marketplace. The interface is colorful, has more flair, and some cool features like ‘Mixview’ that let you quickly see related albums, songs, or other users related to what you’re listening to. Clicking on one of those will center on that item, and another set of “neighbors” will come into view, allowing you to navigate around exploring by similar artists, songs, or users. Speaking of users, the Zune “Social” is also great fun, letting you find others with shared tastes and becoming friends with them. You then can listen to a playlist created based on an amalgamation of what all your friends are listening to, which is also enjoyable. Those concerned with privacy will be relieved to know you can prevent the public from seeing your personal listening habits if you so choose. phone mockup

    ReplyDelete
  8. satellite tv has got to be one of the best inventions that we humans enjoy,” website design la

    ReplyDelete