The official website of Bipul Raman

Working with JSOM (JavaScript Object Model) on SharePoint Apps

No comments

In this article i have written how a developer should start working woith JSOM ( JavaScript Object Model) in SharePoint Apps development. Before going through code sample, these prerequisites to be taken care. 

Prerequisites:

Make sure that these frameworks has been referred in the page:
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<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>
<script type="text/javascript" src="/_layouts/15/SP.RequestExecutor.js"></script>

Note: The sequence of these JS Frameworks should be as it is.

CAML Query:

Sample Query:
"<View Scope='RecursiveAll'>"+
    "<ViewFields>"+
        "<FieldRef Name='FIELD_1' />"+
        "<FieldRef Name='FIELD_2' />" +
    "</ViewFields>" +
"<Query>" +
    "<OrderBy>" +
        "<FieldRef Name='Title' Ascending='False' />" +
    "</OrderBy>" +
"</Query>" +
"<RowLimit>3</RowLimit>" +
"</View>";

Note:
<ViewFields> will load only selective fields
<OrderBy> will do sorting of data by Ascending or Descending
<RowLimit> will restrict the no of rows to be fetched from the list
<Query> may contain additional query which can be easily generated by U2U CAML builder
Intention to mention these parts because using U2U CAML Query builder, you will not get first three directly. But first three is very important from performance point of view. Load only that much data which is required.

Code Samples

Sample code to retrieve list data :
var hostweburl;
var appweburl;
var context;
var appContextSite;
var factory;
var web;
var list;
var listitemcollection;

$(document).ready(function () {
    // Getting values from query string
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));     
    // Calling function to retrive data from list
    GetListData();
});

// Function to retrieve a query string value.
function getQueryStringParameter(paramToRetrive) {
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrive) return singleParam[1];
    }
}

// Function to get existing List data
function GetListData() {
    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostweburl);
    web = appContextSite.get_web();
    list = web.get_lists().getByTitle("YOUR_LIST_NAME");
    var camlString = "YOUR_CAML QUERY GOES HERE";
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(camlString);
    listitemcollection = list.getItems(camlQuery);
    context.load(listitemcollection, "Include(FIELD_1, FIELD_2, FIELD_3)");
    context.executeQueryAsync(GetListSuccess, GetListError);
}

// Function to handle the success event for GetListData.
function GetListSuccess(data, req) {
    var enumerator = listitemcollection.getEnumerator();
    // iterating data from listitemcollection
    while (enumerator.moveNext()) {
        var results = enumerator.get_current();
        // data can be utilised here.. 
        console.log(results.get_item("FIELD_1"));
    }
}
// Function to handle the error event for GetListData
function GetListError(data, error, errorMessage) {
    console.log("Error: " + errorMessage);
}

Sample code to add list data :

var hostweburl;
var appweburl;
var context;
var appContextSite;
var factory;
var web;
var list;
var listitemcollection;

$(document).ready(function () {

    // Getting values from query string
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
     
    // Calling function to add data to list
    AddListData();
});

// Function to retrieve a query string value.
function getQueryStringParameter(paramToRetrive) {
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrive) return singleParam[1];
    }
}

// Function to add new List data
function AddListData() {
    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostweburl);    
    web =  appContextSite.get_web();
    list = web.get_lists().getByTitle("YOUR_LIST_NAME");

    var listItemCreationInfo = new SP.ListItemCreationInformation();
    var newItem = list.addItem(listItemCreationInfo);
    newItem.set_item('FIELD_1', 'VALUE');
    newItem.update();
    context.load(newItem);
    context.executeQueryAsync(AddListSuccess, AddListError);
}

// Function to handle the success event for AddListData.
function AddListSuccess(data, req) {
    console.log("Details added successfully");
}

// Function to handle the error event for AddListData
function AddListError(data, error, errorMessage) {
    console.log("Could not complete cross-domain call: " + errorMessage);
}

Sample code to edit/update list data :

var hostweburl;
var appweburl;
var context;
var appContextSite;
var factory;
var web;
var list;
var listitemcollection;

$(document).ready(function () {

    // Getting values from query string
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
     
    // Calling function to add data to list
    EditListData();
});

// Function to retrieve a query string value.
function getQueryStringParameter(paramToRetrive) {
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrive) return singleParam[1];
    }
}

// Function to edit List data
function EditListData() {
    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostweburl);
    web = appContextSite.get_web();
    list = web.get_lists().getByTitle("YOUR_LIST_NAME");

    var oListItem = list.getItemById('LIST_ITEM_ID');    
    oListItem.set_item('FIELD_1', 'VALUE');
    oListItem.update();
    context.executeQueryAsync(EditListSuccess, EditListError);
}

// Function to handle the success event for EditListData.
function EditListSuccess(data, req) {
    console.log("Details updated successfully");

}

// Function to handle the error event for EditListData
function EditListError(data, error, errorMessage) {
    console.log("Error: " + errorMessage);
}

No comments :

Post a Comment