in

Dot Net Mafia

Group site for developer blogs dealing with (usually) .NET, SharePoint 2013, SharePoint 2010, Office 365, SharePoint Online, and other Microsoft products, as well as some discussion of general programming related concepts.

This Blog

Syndication

Archives

Corey Roth [MVP]

A SharePoint MVP bringing you the latest time saving tips for SharePoint 2013, Office 365 / SharePoint Online and Visual Studio 2013.

How to: Query List Items from the Host Web in a Client Web Part of a SharePoint Hosted app

That’s a mouthful, but I wanted to make sure that people knew exactly what this post is for.  The problem I am seeing out there already is that while there is a lot of code samples, they aren’t clear for what type of app the sample is for.  If you are doing a provider hosted app for example, the way you query list items is different (using the Cross-Domain Library).  Today’s topic boggled me though because while I found plenty of samples on how to query list items using CSOM from an app, they were all in-fact incorrect for a SharePoint hosted app.  The article I linked is great by the way.  It has many of the things you need to know how to do via CSOM in an app so be sure and check it out.

Now to get on to the scenario I want to help you with today.  If you are building a Client Web Part, you may have stumbled upon my previous articles on the topic (JavaScript and Getting Started).  These are great articles to get you started, however, it turns out I left out the details on how to query list items from a SharePoint hosted app.  Like many things, it’s not as simple as I thought it was.  I thought it was just a matter of passing another URL into get_web().  I was wrong.  I then saw some examples and thought I just need to pass the URL into a new SPContext object.  Also wrong.  While, you can do that, once you make the call to get your list items, you’ll quickly find yourself with an Access Denied error coming from MicrosoftAjax.js.  I gave up and posted something to the forums and luckily Elisabeth Olson from MSFT came through with the answer.  In my solution, I start with some global variable declarations.

var context;

var web;

var user;

var spHostUrl;

var parentContext

Then the code looks similar to that from my article on SP.js.  In the document ready function, I get the spHostUrl with the following line of code.  You can get that getQueryStringParameter method from my previous article as well.  Remember, the SPHostUrl comes from the {StandardTokens} parameter in your Client Web Part’s elements.xml file.

spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));

Now, we set up our context and here is where things are a bit different.  First, we get our context object using SP.ClientContext.get_current() as usual.  However, we have to get a new context by using SP.AppContextSite and passing in the current context along with the Host Url.

context = new SP.ClientContext.get_current();

parentContext = new SP.AppContextSite(context, spHostUrl);

After that, we just need to get our SPWeb object using the parentContext.

web = parentContext.get_web();

At this point, it’s business as usual to do our queries.  Get the list, set a CAML query, load the getItems call, and then execute the query.

var list = web.get_lists().getByTitle("My List"));

 

var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml("");

 

this.listItems = list.getItems(camlQuery);

context.load(listItems);

 

context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),

    Function.createDelegate(this, this.onQueryFailed));

My success and failure functions are pretty standard in this case.  I just manually iterate through the results and return the Title and Id.  Otherwise, I display the reason for failure.

function onQuerySucceeded() {

    $("#results").empty();

    var listInfo = '';

    var listEnumerator = listItems.getEnumerator();

 

    listInfo += "<table><tr><th>Id</th><th>Title</th></tr>";

 

    while (listEnumerator.moveNext()) {

        var listItem = listEnumerator.get_current();

        listInfo += '<tr><td>' + listItem.get_item('ID') + '</td>'

            + '<td>' + listItem.get_item('Title') + '</td>'

            + '</tr>\n';

    }

 

    listInfo += '</table>';

 

    $("#results").html(listInfo);

}

 

function onQueryFailed(sender, args) {

    $("#results").empty();

    $("#results").text('Request failed. ' + args.get_message() +

        '\n' + args.get_stackTrace());

}

This threw me for a loop for a while, so hopefully this post helps you get started quicker when you build your app.

Follow me on twitter, @coreyroth, if you have any questions and come see me at SPC if you are going.

Comments

 

How to: Query List Items from the Host Web in a Client Web Part of a SharePoint Hosted app - Corey Roth [MVP] | SharePoint Resources | Scoop.it said:

Pingback from  How to: Query List Items from the Host Web in a Client Web Part of a SharePoint Hosted app - Corey Roth [MVP] | SharePoint Resources | Scoop.it

October 26, 2012 9:01 AM
 

Query List Items from the Host Web | Office365 Wijzer | Scoop.it said:

Pingback from  Query List Items from the Host Web | Office365 Wijzer | Scoop.it

October 29, 2012 5:45 AM
 

Query List Items from the Host Web | SharePoint Wijzer | Scoop.it said:

Pingback from  Query List Items from the Host Web | SharePoint Wijzer | Scoop.it

October 29, 2012 5:54 AM
 

Phillip Demro said:

Don't forget to set up your AppManifest.xml with the necessary permissions!

December 6, 2012 11:05 PM
 

anil said:

hi i need to access the lists items from different site collection ushing SharePoint 2013 Apps

January 29, 2013 7:25 AM
 

CoreyRoth said:

@anil Your best bet then is to use search using the REST interface then.

January 29, 2013 8:14 AM
 

Rolle said:

When I get to the onQuerySucceeded function I test alert(listItems_get_count()); and I always get 0 even there are items in the list. Any ideas why is this?

January 30, 2013 3:26 AM
 

CoreyRoth said:

@Rolle If i had to guess, it's an issue with the query you are using.  Try a simpler one first if possible.

January 30, 2013 8:16 AM
 

Erik said:

Is there a way to do this with anonymous access turned on?

My Client App Part runs fine when a user is logged in. However, when an anonymous user (who has access to the page and the list in question) it blows up with the following error:

Request failed. There is no app context to execute this request. at Microsoft.SharePoint.SPAppContextSite..ctor(String siteUrl) at Microsoft.SharePoint.ServerStub.SPAppContextSiteServerStub.InvokeConstructor(XmlNodeList xmlargs, ProxyContext proxyContext) at Microsoft.SharePoint.Client.ServerStub.InvokeConstructorWithMonitoredScope(XmlNodeList args, ProxyContext proxyContext) at Microsoft.SharePoint.Client.ClientMethodsProcessor.InvokeConstructor(String typeId, XmlNodeList xmlargs) at Microsoft.SharePoint.Client.ClientMethodsProcessor.GetObjectFromObjectPath(XmlElement xe) at Microsoft.SharePoint.Client.ClientMethodsProcessor.GetObjectFromObjectPathId(String objectPathId) at Microsoft.SharePoint.Client.ClientMethodsProcessor.ProcessInstantiateObjectPath(XmlElement xe) at Microsoft.SharePoint.Client.ClientMethodsProcessor.ProcessOne(XmlElement xe) at Microsoft.SharePoint.Client.ClientMethodsProcessor.ProcessStatements(XmlNode xe) at Microsoft.SharePoint.Client.ClientMethodsProcessor.Process()

July 22, 2013 3:43 PM
 

ZZ said:

Hi Corey,

Is it possible to access the SharePoint data via JSOM outside SP APP?

Thanks,

ZZ

October 9, 2013 5:26 AM
 

CoreyRoth said:

@Erik unfortunately, this is a limitation of apps right now.  It just doesn't work with anonymous.

October 11, 2013 10:49 AM
 

VinceSuperC said:

Thanks for the article

I am still seeing some issues and wondered if you can help.

I am creating a Sharepoint hosted app and writing all my code in Client Side Java Script

It appears that the App does not have access to the Web site. I am trying to access Shared Documents from the app and create a folder/ file.

Here is my JavaScript.

Prior to adding the SP.AppContextSite I was getting accessed denied

Now I get the error Request failed: List 'Shared Documents' does not exist at site with URL 'MyUrl'.

Any input would be appreciated?

Vince

function createFolder(resultpanel) {

   var context;

   var web;

   var user;

   var spHostUrl;

   var parentContext;

   spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));

   context = new SP.ClientContext.get_current();

   parentContext = new SP.AppContextSite(context, spHostUrl);

   web = parentContext.get_web();

   var oList = web.get_lists().getByTitle("Shared Documents");

   itemCreateInfo = new SP.ListItemCreationInformation();

   itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);

   itemCreateInfo.set_leafName("My new folder!");

   this.oListItem = oList.addItem(itemCreateInfo);

   this.oListItem.update();

   context.load(this.oListItem);

   context.executeQueryAsync(

       Function.createDelegate(this, successHandler),

       Function.createDelegate(this, errorHandler)

   );

   function successHandler() {

       resultpanel.innerHTML = "Go to the " +

           "<a href='../Lists/Shared Documents'>document library</a> " +

           "to see your new folder.";

   }

   function errorHandler() {

       resultpanel.innerHTML =

           "Request failed: " + arguments[1].get_message();

   }

}

November 17, 2013 6:06 AM
 

CoreyRoth said:

@VinceSuperC I don't really see any issues with that code.  It seems like it should work.  Verify the URL is coming across right and double check the list name.

November 27, 2013 10:17 AM
 

How to get empty href query parameters? | Yundt Answers said:

Pingback from  How to get empty href query parameters? | Yundt Answers

December 12, 2014 1:19 AM
 

Juninho Santos said:

Hi, Corey!

I saw your comment "unfortunately, this is a limitation of apps right now.  It just doesn't work with anonymous." and i got worried.

I am facing de same problem with my applications. I am trying to deploy these apps in a  public facing site  (anonymous).

What are the options in this case. I just want to create a simple contact form that sends an e-mail e add a information in a list?

January 13, 2015 2:57 PM
 

CoreyRoth said:

@Juninho I am afraid we are a bit limited right now.  I am not sure there are any options.

January 13, 2015 6:44 PM
 

Lubna Karody said:

Good Post !:)

October 13, 2015 2:35 AM

Leave a Comment

(required)  
(optional)
(required)  
Add

About CoreyRoth

Corey Roth is an independent SharePoint consultant specializing in ECM, Apps, and Search.
2015 dotnetmafia.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems