0

I'm using the following code part to access the host web from a sharepoint add-in :

var ctx = SP.ClientContext.get_current();

var factory = new SP.ProxyWebRequestExecutorFactory(this.appWebUrl);
ctx.set_webRequestExecutorFactory(factory);

var appContextSite = new SP.AppContextSite(ctx, caller.parent.srcUrl);
var hostweb = appContextSite.get_web();
ctx.load(hostweb);
console.log("URL: "+hostweb.get_lists().get_count());

However, when it call the console log, i get "The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested" returned. caller.parent.srcUrl does contain the absolute URL of the site collection.

1

We have to use executeQueryAsync method to sent the request and get the response from SharePoint. The below code snippet can help you,

var hostweb = appContextSite.get_web();
var lists = hostweb.get_lists();
ctx.load();
        ctx.executeQueryAsync(Function.createDelegate(this,
                function() {
                    alert("List Collection Count: " + lists.get_count());
                }
            ),
            Function.createDeletage(this, function(err) {
                alert(err);
            })
        );
  • 1
    Note: debugging with alert will take a of time, learn to use the F12 Dev Tools: developer.microsoft.com/en-us/microsoft-edge/platform/… And the Function.createDelegate wrapper around the function definition was only needed in IE8 days: sharepoint.stackexchange.com/questions/164893/… – Danny '365CSI' Engelman Jul 25 '16 at 11:07
  • @Danny, Sure, I agree with it. Thanks for the note. – Shantha Kumar Thambidurai Jul 25 '16 at 11:15
  • Thank you for your response. Even if i write get_count() or anything related to get_lists into the ctx.executeQueryAsync part it returns the same error as before. hostweb.get_url() does point to the right URL, but hostweb.get_lists() does not contain any of the lists of said site collection. – Thun Jul 25 '16 at 11:27
  • Even though this answer didn't work for me, Shanthas post lead me to the right solution. I needed the lists variable described by him via "var lists = hostweb.get_lists() and needed to ctx.load(lists) before i used ctx.executeQueryAsync(). – Thun Jul 25 '16 at 12:22
  • Shantha missed the ); at the end of the load line... but its always better to learn from mistakes than just copy/paste and not having a clue what code actually does. – Danny '365CSI' Engelman Jul 25 '16 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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