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.


23 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
    Replies
    1. Great Article android based projects

      Java Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

      Delete
  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
  9. Substantially, the post is actually the greatest on that worthw hile topic. I harmonise with your conclusions and also will certainly thirstily look forward to your coming updates. Simply saying thanks definitely will not just be adequate, for the extraordinary lucidity in your writing. I can immediately grab your rss feed to stay abreast of any updates. Fabulous work and much success in your business enterprize! windows 10x devices

    ReplyDelete
  10. actually, i like the body of Daniel Craig. wish i could have a body like that’ airpods case

    ReplyDelete
  11. It can likewise be utilized alongside HTML5 and CSS for making web applications and games. So you can generally consider involving JavaScript as a unique customer side programming language for building huge scope web applications.https://twitchviral.com/

    ReplyDelete
  12. I’m really loving the theme/design of your blog. Do you ever run into any web browser compatibility problems? A few of my blog audience have complained about my site not operating correctly in Explorer but looks great in Opera. Do you have any recommendations to help fix this issue? Casino Online

    ReplyDelete
  13. I simply could not depart your site before suggesting that I really loved the usual information an individual supply in your visitors? Is gonna be again frequently to inspect new posts. Federal Premium Heavyweight TSS Turkey Ammunition 20 Gauge

    ReplyDelete
  14. Anabolic steroids are used to enhance performance, the question is, should you be concerned about the physical effects of steroids? There is no perfect steroid, they all have side effects. Homepage

    ReplyDelete
  15. Great post right here. One thing I’d like to say is that often most professional areas consider the Bachelor Degree like thejust like the entry level standard for an online degree. Whilst Associate Certification are a great way to begin, completing your own Bachelors uncovers many opportunities to various employment opportunities, there are numerous online Bachelor Diploma Programs available coming from institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another concern is that many brick and mortar institutions give Online variations of their college diplomas but commonly for a greatly higher payment than the companies that specialize in online higher education degree plans. counts on this post

    ReplyDelete
  16. This particular Are generally Weight Loss diet will be an very and flexible sticking to your diet training planned for those who find themselves looking for to get slimmer body moreover eventually maintain a significantly more healthy life style. weight loss 스웨디시

    ReplyDelete
  17. As I website possessor I think the articles here is very wonderful, regards for your efforts. 셔츠룸

    ReplyDelete
  18. The N-Strike Raider Rapid Fire CS-35 is one of NERF's new Nerf guns for 2009. Released in early September of 2009, the Raider Rapid Fire is a 35 round beast that will forever change how you NER. why not find out more

    ReplyDelete
  19. Unfortunately, with addiction, there isn't one death but a series. One by one, each one takes you lower. By the time the darkness has taken over, the addict is usually too weak to handle the crawl out of the pit. Comatose

    ReplyDelete
  20. Hello! I merely would want to make a enormous thumbs up for your excellent info you might have here during this post. I will be returning to your blog for additional soon. 강남가라오케

    ReplyDelete
  21. Nice post. I learn some thing very complicated on diverse blogs everyday. It will always be stimulating to learn to read content using their company writers and rehearse something from their site. I’d want to use some with all the content in this little blog regardless of whether you do not mind. Natually I’ll provide link on your own internet blog. Thank you sharing. 강남셔츠룸

    ReplyDelete