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 Answers 3

23

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());
}
3

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

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

9
  • 1
    With or without I get the same error.
    – John S
    Apr 30, 2012 at 20:37
  • Just did a quick edit, try my second suggestion.
    – James Love
    Apr 30, 2012 at 20:38
  • 1
    Same for that one too
    – John S
    Apr 30, 2012 at 20:41
  • Balls. If you go to your Javascript console, does typing 'SP' come back with anything?
    – James Love
    Apr 30, 2012 at 20:42
  • Yea, {...} but thats it
    – John S
    Apr 30, 2012 at 20:49
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);
        }
    }

Your Answer

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

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