1

I'm trying to obtain values from a SharePoint 2010 list. The List name is "SitesList" at the URL of "servername/sites/dev/Lists/SitesList/AllItems.aspx". The Columns that I would like to print on the alert message "Title" and "URL."

Once I run everything, the page loads but nothing happens at all. I can see that my web part is there and I even switched out the code to something simple like an alert message and it works. What am I doing wrong?

<script type="text/javascript">
var siteUrl = '/sites/dev/';

function retrieveListItems() {

    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('SitesList');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><Where><Geq><FieldRef Name=\'ID\'/>" + "<Value     Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>");
    this.collListItem = oList.getItems(camlQuery);

    clientContext.load(collListItem);

    clientContext.executeQueryAsync(Function.createDelegate(this,     this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

}

function onQuerySucceeded(sender, args) {

    var listItemInfo = '';

    var listItemEnumerator = collListItem.getEnumerator();

    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += '\nID: ' + oListItem.get_id() +
        '\nTitle: ' + oListItem.get_item('Title') +
        '\nURL: ' + oListItem.get_item('URL');
    }

    alert(listItemInfo.toString());
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

1 Answer 1

1

It looks like you're never actually triggering the retrieveListItems function.

Try adding this at the top of you script, after the var siteUrl:

<script type="text/javascript">
var siteUrl = '/sites/dev/';

ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");

function retrieveListItems() {
...
}
...
</script>

This is SharePoint specific and will wait for SP.JS to load before executing the retrieveListItems function.

This is typically a more recommended approach than jQuery's document.ready function, or native JS's self executing functions as many things happen behind the scenes with SharePoint apps after the page loads.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.