12

I am trying to get some information about the current context through the sharepoint javascript object model and am getting annoying errors.

$(document).ready(function () { ExecuteOrDelayUntilScriptLoaded(loadConstants, "sp.js"); });

function loadConstants() {

var ctx = new SP.ClientContext.get_current();

var site = ctx.get_site();
IPC_siteUrl = site.get_url();
IPC_siteId = site.get_id();

var web = ctx.get_web();
}

This is what im calling in a javascript file in our core javascript file, and when i try to call "ctx.get_site()" I am getting errors through the dev console on ie8.

The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

Im not sure why this is happening as im following Microsofts directions.

Any thoughts?

3 Answers3

22

The SharePoint Client Side Object Model works a bit different as on the server side. Before you can use an object you must first load it and then you must execute a query to retrieve the object.

In this blogpost you can find a description how to use it.

$(document).ready(function () { ExecuteOrDelayUntilScriptLoaded(loadConstants, "sp.js"); });

function loadConstants() {

var ctx = new SP.ClientContext.get_current();

this.site = ctx.get_site();
ctx.load(this.site );
this.web = ctx.get_web();
ctx.load(this.web);
ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFail));


}

function onSuccess(sender, args) {
   IPC_siteUrl = this.site.get_url();
   IPC_siteId = this.site.get_id();
}
funtion onFail(sender, args) {
    console.log(args.get_message());
}
yannisgu
  • 471
  • 2
  • 3
2

Try it, its working :

var clientContext;

$(document).ready(function () {
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', execOperation);
    });

function execOperation() {
        try {
            clientContext = new SP.ClientContext.get_current();                   
        }
        catch (err) {
            alert(err);
        }
    }
Ronak Patel
  • 3,261
  • 3
  • 23
  • 45
2

Don't think you need the new keyword on get_current()

Or if you do, it's just new SP.ClientContext(); I think

James Love
  • 25,512
  • 2
  • 45
  • 77