Using JSOM to query SharePoint 2013 lists with Taxonomy Fields

So, I’d an interesting problem. I have a SharePoint 2013 list that uses a Managed Metadata (or ‘Taxonomy’) field. I need to, through the JavaScript Client Object Model, get all items that have a particular value or a child of that value on the taxonomy tree. As an example, here’s my taxonomy:termSet Sounds like it should be simple to query this, right? Well, not so much. Continue reading “Using JSOM to query SharePoint 2013 lists with Taxonomy Fields”

Advertisements
Using JSOM to query SharePoint 2013 lists with Taxonomy Fields

Issues with getting the SP.ClientContext in SharePoint 2013

So, I’m migrating a solution from SP2010 to 2013. In the JavaScript for part of the solution, I use the JavaScript client-side object model (JSOM). This involves getting the current ClientContext for the site:

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

Unfortunately, ClientContext was null, so I kept getting Null Reference exceptions.

“Weird”, I thought, “This worked in 2010”. Now, my solution has a very similar piece of code elsewhere in it, so I went and tested it – and it worked. Even weirder.

Next up, I tried using a SP.SOD.executeOrDelayUntilScriptLoaded() call around the code where I got the ClientContext. Surely it was just a matter of waiting for the JavaScript file ‘sp.js’ to load? Well, it never loaded. With these two lines…

SP.SOD.executeOrDelayUntilScriptLoaded(function () { alert('SP.Runtme.js Loaded'); }, 'SP.Runtime.js');
SP.SOD.executeOrDelayUntilScriptLoaded(function () { alert('SP.js Loaded'); }, 'SP.js');

…no alerts were shown. On the page that works, they both get shown nearly instantly.

Okay, so it’s not my code then, it’s that the JSOM isn’t initializing, but only on one particular page. That sucks. What can I do to initialise it? Well, I found this post describing the same problem, but for publishing pages. Mine isn’t – it’s an application page – but I suspected it might be the same issue. And I checked MSDN which describes initialising sp.js.

I added this line:

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { });

And my code began working again on this page. So it seems that for some pages in SharePoint 2013 the Client Object Model isn’t necessarily initialized.

Issues with getting the SP.ClientContext in SharePoint 2013