Using 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.

We’ll cover

  1. Some concepts with using JavaScript, JSOM and SharePoint
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:

<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.

_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:

  <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.

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.

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

Querying a list

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.

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.

<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.

  //common code used for submitting the batch
  clientContext.load(SharePoint object);
  clientContext.executeQueryAsync(onSuccess, onError);
  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

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

Updating a List item

Simple types

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

Url Field

  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:

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

Creating a permission Level

  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

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

  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

  // 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.

Get Free Email Updates!

Signup now and receive an email once I publish new content.

I will never give away, trade or sell your email address. You can unsubscribe at any time.

  • Isaac Sogunro

    Awesome. Thanks! How would you update?