Click here to Skip to main content
15,892,927 members
Articles / Productivity Apps and Services / Sharepoint
Technical Blog

Using JavaScript or JQuery and JSOM in SharePoint

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
5 Jan 2016CPOL4 min read 16.8K   1  
How to use JavaScript or JQuery and JSOM in SharePoint

In this article, we’ll see how to plug in some JavaScript and use the JavaScript object model or JSOM to interact with SharePoint. The advantage with JSOM is that it allows you to batch the requests to the server.

It would also be easier to make REST API calls from JavaScript. And, it would be easier to work with the return data like json from these REST calls using JavaScript as well.

JavaScript code in SharePoint runs within the context of the current logged in user. It has to be loaded from within a SharePoint artifact or context such as a page or a form. It cannot be executed from outside of SharePoint like CSOM.

To add some custom JavaScript functionality, first, create the JavaScript file and add your custom js code. You could deploy this to the layouts folder or to a SharePoint library such as style library or site assets library.

Next, you need to add a reference to the JavaScript location in the page where you want to call this functionality. Or, you can also add it to the master page if you want it to be available across all the pages in your site collection. Suppose, you have added a file called CustomJavaScript.js in the layouts folder, you can add a reference as follows:

HTML
<script src="/_layouts/15/CustomJavaScript.js" type="text/javascript"></script>

If you plan to use jQuery, I think it is a good idea to use the following inbuilt SharePoint function instead of using the jQuery’s document ready function. This is because SharePoint uses this onload function and it may collide with the jQuery document ready function. Also, it gives you control over the order in which your functions are executed.

JavaScript
_spBodyOnLoadFunctionNames.push("functionName1");
_spBodyOnLoadFunctionNames.push("functionName2");

function functionName1(){
    //function body
}
function functionName2(){
    //function body
}

If you want to use the JavaScript object model, then you have to load two libraries SP.Runtime.js and SP.js. You can load the scripts programmatically as shown below. Otherwise, you can use the declarative approach and add a ScriptLink control to the page such as:

JavaScript
<SharePoint:ScriptLink Name="SP.js" LoadAfterUI="true"
Localizable="false" runat="server" ID="SP" />

Using JSOM

Checking the Permission Levels of User

Let’s see how we can retrieve the web object and check the permission levels of the current logged in user.

JavaScript
function functionName1(){
  SP.SOD.executeFunc('SP.Runtime.js', 'SP.ClientContext',
    function() {
      SP.SOD.executeFunc('SP.js', 'SP.ClientContext',
      function() {
        var siteUrl = _spPageContextInfo.webAbsoluteUrl;
        var clientContext = new SP.ClientContext(siteUrl);
        var web = clientContext.get_web();
        clientContext.load(web, 'Title', 'EffectiveBasePermissions');
        clientContext.executeQueryAsync(onSuccess, onError);
      });
  });
}
function onSuccess(){
  alert('Title: ' + web.get_title());
  var permissions = SP.PermissionKind.manageWeb && SP.PermissionKind.viewListItems;
  if(web.get_effectiveBasePermissions().has(permissions)){
    alert('user has the required permissions');
  }
}
function onError(sender, args) {
  alert(args.get_message() + '\n' + args.get_stackTrace());
}

Notice that we are explicitly loading the Title and EffectiveBasePermissions properties as we are only using those properties. In this case, the other properties will not get loaded. It is a best practice to load only the properties we need as it will reduce the network load by limiting the data returned from the server.

Also, it is better to load the properties we need this way because if we don’t, we cannot assume that all the properties will be loaded by default. So, we might get a PropertyOrFieldNotInitializedException if it is not loaded by default.

Retrieving a Lists Collection

Here, we are loading only the Title and Id properties from the lists collection. Notice the difference in syntax for loading specific properties between individual object such as Web and collections of objects such as the Lists collection. For collection of objects, use the Include syntax.

JavaScript
var lists = web.get_lists();
clientContext.load(lists, 'Include(Title, Id)');

Querying a List

JavaScript
var list = lists.getByTitle('List Title');
var query = new SP.CamlQuery();
query.set_ViewXml("<View><Query>query expression</Query></View>");
var listItems = list.getItems(query);
clientContext.load(listItems);
clientContext.executeQueryAsync(onSuccess, onError);
function onSuccess(){
  var enumerator = listItems.getEnumerator();
  while(enumerator.moveNext()) {
    alert(enumerator.get_current().get_item("Title"));
  }
}

Another way to load the results is using Queryable Load. If we use this method, we can directly loop over the collection instead of using an enumerator.

JavaScript
var listItems = clientContext.loadQuery(listItems);

function onSuccess(){
  for(var i=0; i<results.length; i++) {
    alert(results[i].get_item("Title"));
  }
}

Creating a List

For Create, Update and Delete requests, we need to have a form digest on the page. It can also be added to the master page. This is mandated by SharePoint to protect against script replay attacks.

JavaScript
<SharePoint:FormDigest runat="server"/>

In the following examples, load and execute code (listed below) is common. So, I have omitted it for brevity in the examples.

JavaScript
//common code used for submitting the batch
clientContext.load(SharePoint object);
clientContext.executeQueryAsync(onSuccess, onError);
JavaScript
var listCreationInfo = new SP.ListCreationInformation();
listCreationInfo.set_templateType(SP.ListTemplateType.announcements);
listCreationInfo.set_title("My Announcements");
listCreationInfo.set_quickLaunchOption(SP.QuickLaunchOptions.on);

var list = lists.add(listCreationInfo);

Creating a List Item

JavaScript
var itemCreationInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(itemCreationInfo);
listItem.set_item("Title", "Test Title");
listItem.update();

Updating a List Item

Simple types:

JavaScript
var listItem = list.getItemById(1);
listItem.set_item("Title", "New Title");
listItem.update();

Url Field

JavaScript
var url = new SP.FieldUrlValue();
url.set_url("http://www.google.com");
url.set_description("Google");
listItem.set_item("UrlField", url);
listItem.update();

Deleting SharePoint Artifacts

Deleting is similar for all SharePoint artifacts. First, retrieve the object in the standard way. Then, call the deleteObject method and submit the batch. For example, deleting a list item is as follows:

JavaScript
listItem.deleteObject();
// load the list object and submit the batch

Creating a Permission Level

JavaScript
var site = clientContext.get_site();
var reqPermissions = new SP.BasePermissions();
reqPermissions.set(SP.PermissionKind.editListItems);
reqPermissions.set(SP.PermissionKind.viewListItems);

var roleDefCI = new SP.RoleDefinitionCreationInformation();
roleDefCI.set_name("Group Name");
roleDefCI.set_description("Group Desc");
roleDefCI.set_basePermission(reqPermissions);

var roleDef = site.get_rootWeb().get_roleDefinitions().add(roleDefCI);

var bindings = SP.RoleDefinitionBindingCollection.newObject(clientContext);
bindings.add(roleDef);

list.breakRoleInheritence(true, false);

var assignments = list.get_roleAssignments();
var roleAssignment = assignments.add(web.get_currentuser(), bindings);

Getting SharePoint Groups

JavaScript
var groups = web.get_siteGroups();

In the success handler, we need to access the individual group as groups.itemAt(1), etc.

Adding a User to a Group

JavaScript
var user = web.ensureUser("domain\\user");
var group = groups.getByName("GroupName");
var usersInGroup = group.get_users();
usersInGroup.addUser(user);
//load the user, group and users collection and submit the batch

Removing a User from a Group

JavaScript
// load the user collection
usersInGroup.remove(user);
//load the user and group and submit the batch

For more examples on using JSOM, check out the MSDN article Complete basic operations using JavaScript library code in SharePoint 2013

However, in the MSDN article, $.getScript is used to load the library scripts like SP.js. This did not work for me. Also, instead of jQuery document ready functions as mentioned in the article, I think it is better to use the _spBodyOnLoadFunctionNames.

In this article, we saw how we can add JavaScript code to SharePoint artifacts. And, we went over several common scenarios of working with SharePoint using JavaScript object model.

The post Using JavaScript or JQuery and JSOM in SharePoint appeared first on The SharePoint Guide.

This article was originally posted at http://www.thesharepointguide.com/sharepoint-javascript

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --