Using JavaScript Client Context Code:
var clientContext = new SP.ClientContext.get_current();
after above Code execute error I get the following error
SP.ClientContext is undefined
in Client Context Code
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It only takes a minute to sign up.
Sign up to join this communityUsing JavaScript Client Context Code:
var clientContext = new SP.ClientContext.get_current();
after above Code execute error I get the following error
SP.ClientContext is undefined
in Client Context Code
You got the error because the 'SP.ClientContext'
in 'sp.js'
is not loaded
Now, Add your context code in a function
function myFunction() {
var clientContext = new SP.ClientContext.get_current();
...
}
Then, call the function as below which ensures the file 'sp.js'
containing 'SP.ClientContext'
function is loaded first and then runs 'myFunction'
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', myFunction);
You need to make sure sp.js
file is loaded before you can access CSOM.
Use a code structured like this, in the same .js
file:
$(document).ready(function () {
//Do not execute jsom until sp.js file has loaded.
ExecuteOrDelayUntilScriptLoaded(myFunctionToBeExecuted, "sp.js");
});
The ExecuteOrDelayUntilScriptLoaded(function1, jsFile.js)
makes sure that your function1
is only called after jsFile.js
is loaded. It's safer to place this within a jQuery $(document).ready(function(){});
to make sure your function gets called when everything else is ready.
Now you go ahead and just define your function. So at the end your code should look like:
$(document).ready(function () {
//Do not execute jsom until sp.js file has loaded.
ExecuteOrDelayUntilScriptLoaded(myFunctionToBeCalled, "sp.js");
});
function myFunctionToBeCalled(){
var clientContext = new SP.ClientContext.get_current();
// Rest of your code ...
}
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
Use ExecuteOrDelayUntilScriptLoaded
Reference link