0

I am trying to get a site title property using JSOM, but i get can't read prperty 'title' of undefined. Can someone help me understand this error message?

function getRootWeb() {
    //Get and load a reference to the root web of the current site collection.
    var ctx = new SP.ClientContext("http://Server/sites/sitecollection/");
    var site = ctx.get_site();
    var rootWeb = site.get_rootWeb();

    ctx.load(rootWeb);
    //Ask SharePoint to pull data for us
    ctx.executeQueryAsync(onQuerySucceed,onQueryFailed);
};

//Function executed on success
 function onQuerySucceed() {
    alert(this.rootWeb.get_title());
};

//Function executed on failure
function onQueryFailed(sender, args) {
    alert('Unable to retrieve data from the SharePoint. Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
};
1

It looks like rootWeb is out of scope in your OnQuerySucceed function. When you first define it using var, it is in the scope of your getRootWeb function. When you call this.rootWeb it is looking for a rootWeb variable with global scope. Change the line where you first define rootWeb to use this:

this.rootWeb = site.get_rootWeb();

0

You need to get rid of this.

Also, you can write it inside the anon function instead of a specific success or failure function:

function getRootWeb() {
    //Get and load a reference to the root web of the current site collection.
    var ctx = new SP.ClientContext("http://Server/sites/sitecollection/");
    var site = ctx.get_site();
    var rootWeb = site.get_rootWeb();

    ctx.load(rootWeb);
    //Ask SharePoint to pull data for us
    ctx.executeQueryAsync(function(){
        // success function
        alert(rootWeb.get_title());
    },function(sender, args){
        // failure function
        alert('Unable to retrieve data from the SharePoint. Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    });
};

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.