In the code below I can get the value of the ListItemID of a List.
var siteUrl = 'https://company.sharepoint.com/sites/demo';
var t;
retrieveListItemsInclude();
alert("after"+t);
function retrieveListItemsInclude() {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('My tasks');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><OrderBy><FieldRef Name="ID" Ascending ="FALSE"><RowLimit>1</RowLimit><OrderBy></View>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem, 'Include(Id)');
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
alert('inside'+t);
}
function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '\nID: ' + oListItem.get_id();
}
t=listItemInfo;
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
I need to set the value of the listItemID to a global variable e.g.t.
The variable listItemInfo is declared inside the inside onQuerySucceeded function. The scope of the listItemInfo is limited to the onQuerySucceeded function.
I need to pass it to the gobal variable.
1)Can I set the return value in OnSuccesded funcation and set it to another value.
If I add an alert inside the onQuerySucceeded()
function . I get the value of the function.
I have set the value of the global variable t=listItemInfo.
When I alert the value of t inside the parent retrieveListItemsInclude()
function. I get an undefined value.
I understand that the ExecuteQueryAync()
function is an asynchronous function but I am facing the following issues
1) I get an undefined value after the retrieveListItemsInclude();
is called
2) If I change the call the ExecuteQueryAsync function to
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
3) The above code change did not make any difference but worked strangely. When I paste the code in firebug . The first time I get an undefined value but the next the value of the ID. Could this be due to caching.
What is the best way to return a value from the QuerySucceded function.
4) In IE when I edit the page the code works but when I stop editing the page it does not work. Do I need to provide the path for the SP.JS file explicitly or am I missing something