CustomCodes‎ > ‎

SharePoint Hosted app - Getting cross domain list data using JSOM CAML

// Getting list data from cross domain using JSOM

// The allAnnouncements variable is used by more than one

// function to retrieve and process the results.

var allAnnouncements;

var hostweburl;

var appweburl;

// Load the required SharePoint libraries

$(document).ready(function () {

hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));

appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

// Load the js files and continue to the successHandler

$.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js", execCrossDomainRequest);

});

// Function to prepare and issue the request to get List data

function execCrossDomainRequest() {

var context = new SP.ClientContext(appweburl);

appContextSite = new SP.AppContextSite(context, hostweburl);

var web = appContextSite.get_web();

var list = web.get_lists().getByTitle("MyCountryList");

var camlString = "<View Scope='RecursiveAll'><Query><OrderBy><FieldRef Name='Title' Ascending='False' /></OrderBy></Query><RowLimit>3</RowLimit></View>";

var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml(camlString);

allcountries = list.getItems(camlQuery);

context.load(allcountries, "Include(Title, Code)");

context.executeQueryAsync(

successHandler, errorHandler

);

}

// Function to handle the success event.

// Prints the data to the page.

function successHandler(data, req) {

var innerData = "<div><span><b>Country</b></span>&nbsp;&nbsp;<span><b>Country Code</b></span></div>"

var enumerator = allcountries.getEnumerator();

while (enumerator.moveNext()) {

var results = enumerator.get_current();

innerData = innerData + "<div><span>" + results.get_item("Title") + "</span>&nbsp;&nbsp;<span>" + results.get_item("Code") + "</span></div>";

}

document.getElementById("JSOMMethod").innerHTML =

innerData;

}

// Function to handle the error event.

// Prints the error message to the page.

function errorHandler(data, error, errorMessage) {

document.getElementById("JSOMMethod").innerText =

"Could not complete cross-domain call: " +

errorMessage;

}

// 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];

}

}