Saturday, August 23, 2014

SharePoint 2013 - Retrieve all items from a SharePoint list using JavaScript Object Model (JSOM)

In the previous post we discussed the basics of JavaScript Object Model (JSOM)In this post, we will implement JSOM inside a Content editor webpart. As per your requirement you can implement JSOM inside a Site page, Application page or a Master page directly.

Create a custom list for retrieving data from client side
Create a custom list named "Products" with three columns TitleDescription and Price.

Code for retrieving all items from a SharePoint list
In the previous post we have already discussed about the objects and methods used in JSOM. Following is complete code for implementing JSOM for retrieving all items from a SharePoint list.
Code Snippet
  1. <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
  2. <script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
  3. <script type="text/javascript" src="_layouts/15/sp.js"></script>
  4.  
  5. <script type="text/javascript">
  6.     function GetProducts() {
  7.         var clientContext = new SP.ClientContext.get_current();
  8.         var oList = clientContext.get_web().get_lists().getByTitle('Products');
  9.         this.collListItem = oList.getItems("");
  10.  
  11.         clientContext.load(collListItem);
  12.         clientContext.executeQueryAsync(
  13.             Function.createDelegate(thisthis.onQuerySucceeded),
  14.             Function.createDelegate(thisthis.onQueryFailed)
  15.         );
  16.     }
  17.  
  18.     function onQuerySucceeded(sender, args) {
  19.         var ProductInfo = '';
  20.         var listItemEnum = collListItem.getEnumerator();
  21.  
  22.         while (listItemEnum.moveNext()) {
  23.             var oListItem = listItemEnum.get_current();
  24.             ProductInfo += '\n\nID: ' + oListItem.get_id() +
  25.                 '\nTitle: ' + oListItem.get_item('Title') +
  26.                 '\nDesc: ' + oListItem.get_item('Description') +
  27.                 '\nPrice: ' + oListItem.get_item('Price');
  28.         }
  29.  
  30.         alert(ProductInfo.toString());
  31.     }
  32.  
  33.     function onQueryFailed(sender, args) {
  34.         alert('Request failed. ' + args.get_message() +
  35.             '\n' + args.get_stackTrace());
  36.     }
  37. </script>​
  38.  
  39. <input type="button" value="Get Products" onclick="GetProducts()"/>

Copy the above code in a Content editor web part
Go to the SharePoint site and add a content editor web part.

Choose the Edit Source option and the HTML source window will pop up.

Copy the code mentioned in the previous step and paste it inside the HTML source window as follows. Click OK button and save the page.

Displaying the data
Click on the "Get Products" button and all the list items in the Products list will be displayed as an alert.

Sunday, August 10, 2014

SharePoint 2013 - The JavaScript Object Model (JSOM)

In this post we shall look a little deep into the JavaScript Object Model in SharePoint 2013. In the next post we will see a demo for retrieving list items from a SharePoint list using JSOM.

JSOM Objects
Objects in JSOM are pretty much similar to the classes in SharePoint server object model. Following are some of the commonly used JSOM counter parts.
.NET Server type
JSOM object
SPSite
SP.Site object (sp.js)
SPWeb
SP.Web object (sp.js)
SPWebCollection
SP.WebCollection object (sp.js)
SPList
SP.List object (sp.js)
SPListItem
SP.ListItem object (sp.js)
SPListItemCollection
SP.ListItemCollection object (sp.js)
Client context not available
SP.ClientContext object (sp.js)
SPContentType
SP.ContentType object (sp.js)
SPContext
SP.RequestContext object (sp.js)

JSOM Implementation
Following are the main steps for implementing JSOM.
1) Add reference to the JavaScript libraries that support JSOM.
2) Get an instance of Client Context and load the JSOM objects
3) Specify Callback functions and Execute the query.

Now lets see each of the above mentioned steps in detail. After that we will see a demo for getting the items from a SharePoint list using JSOM.

1) Adding reference to the JS libraries for supporting JSOM
For implementing JSOM, a reference to the following JS files should added inside the page.
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="_layouts/15/sp.js"></script>

Note:- In case we have customized or utilized a new master page for our sites, we should ensure that JSOM is loaded before we start accessing it. There are 2 methods for doing in it.
(i) ScriptLink : Use the server side ScriptLink class to declaratively register a script. The class provides properties and methods for registering scripts so that they can be requested when the page is being rendered.
<SharePoint:ScriptLink ID="registerSP" runat="server" OnDemand="true" LoadAfterUI="true" Name="SP.js">
(ii) ExecuteOrDelayUntilScriptLoaded : The SOD framework provides methods to ensure that the client scripts are loaded before any execution takes place on the dependent methods. Calling the following method before the executing method ensures that the function provided in the first parameter is not executed until the script file name mentioned is not loaded or has not been loaded.
ExecuteOrDelayUntilScriptLoaded(GetProducts, "sp.js");

2) Get an instance of client context and load the JSOM objects
First of all, an instance of the client context must be created to access the objects in the JSOM. The current context can be get by using the get_current() method in SP.ClientContext as shown below.
var clientContext = new SP.ClientContext.get_current();

Using the Client Context object all the other SharePoint objects should be loaded as follows. In the following example we are loading all the items from the list named "Products".
var oList = clientContext.get_web().get_lists().getByTitle('Products');
this.collListItem = oList.getItems("");
clientContext.load(collListItem);

Note: You can further add a CAML query to the above code as follows 
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +'<Value  type=\'Number\'>1</Value></Geq></Where></Query>' + '<RowLimit>10</RowLimit></View>');
this.collListItem = oList.getItems(camlQuery);


3) Specify the callback functions and execute the query
Once all the necessary objects are loaded, we must specify the callback functions and execute the query as follows.
clientContext.executeQueryAsync(
Function.createDelegate(thisthis.onQuerySucceeded),
Function.createDelegate(thisthis.onQueryFailed));

Specify the Callback function if query execution succeeded

function onQuerySucceeded(sender, args) {
alert("Success");
}
Specify the Callback function if query execution failed
function onQueryFailed(sender, args) {
alert("Failure");
}

Hope this post helps you to get a basic idea about the JavaScript object model in SharePoint 2013. In the next post we will see a demo for retrieving list items from a SharePoint list using JSOM.