Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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>
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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!

share|improve this answer
    
That did it! Thanks!!!! –  mwilson Jul 16 '13 at 23:27
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.