Wednesday, April 20, 2011

ECMA Script Client Object Model Error: The property or field has not been initialized…


I wrote the following code:

function initialize()
{
ctx = new SP.ClientContext.get_current();
currentweb = ctx.get_web();
ctx.load(currentweb, 'Id');
var webid = currentweb.get_id();
 
ctx.executeQueryAsync(Function.createDelegate(this, onSuccess), Function.createDelegate(this, onFail));
}


Notice the bold and italic line of code that will generate the following error:
Message: 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.

Solution:

  • Add ExecuteOrDelayUntilScriptLoaded(initialize,'SP.js'); in the code block to ensure the SP.js fully loaded before using it.
  • Place var webid = current web.get_id() in the function onSuccess. It seems that you can get the web properties in the same function of it’s being loaded

No comments: