I am using Javascript to create a CAML Query to get data from a list in Sharepoint 2013. It works perfectly. Instead of pushing it to HTML, I need to push the output to a variable as a string for use in another function. My issue is, the output shows in the console from the call within the code, but the variable is empty outside of the code, even though my variable is global. What am I missing?
var optionInfo = '';
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', GetProps);
function GetProps() {
var hclientContext = new SP.ClientContext('http://mysite');
var hList = hclientContext.get_web().get_lists().getByTitle('mylist');
// New caml for getting list based on view
var camlQueryHR = new SP.CamlQuery();
camlQueryHR.set_viewXml('<View Scope="RecursiveAll"><Query>' +
'<OrderBy><FieldRef Name="Title" Ascending="True" /></OrderBy>' +
'</Query><RowLimit>500</RowLimit><ViewFields>' +
'<FieldRef Name="Sub_x0020_Type" /><FieldRef Name="Title" /></ViewFields><QueryOptions>' +
'<ViewAttributes Scope="Recursive" /></QueryOptions></View>');
this.hcollListItem = hList.getItems(camlQueryHR);
// end of caml for list view
//this.ncollListItem = nList.getItems("");
hclientContext.load(hcollListItem);
hclientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onQuerySucceeded(sender, args) {
var hlistItemEnum = hcollListItem.getEnumerator();
while (hlistItemEnum.moveNext()) {
var hListItem = hlistItemEnum.get_current();
var propName = hListItem.get_item('Title');
optionInfo += '<option value="' + propName + '">' + propName + '</option>';
}
console.log("Output within CAML:" + optionInfo); //Appears as expected
//$('.locations').append(optionInfo);
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
console.log("Output outside of CAML:" + optionInfo); //shows as an empty string