SharePoint 2013 apps: Access data in Host web

Recently I got rolled off from a SharePoint 2010 project for few weeks. So, I decided to spend some of my free time on SharePoint 2013. Since apps are a new concept in SP 2013 I decided to create some sample apps. I did not make any production apps as I am yet to get allocated on a project which uses SP 2013 apps. In this series of blog posts I will try to share my leanings. 
This series will consist of following posts:
Develop SharePoint 2013 apps with NAPA
Access data in Host web
Isolated App domain Setup Issues
Create SharePoint Hosted App in Visual Studio
Provider Hosted App Development Prerequisites
App Event Receivers
Remote Event Receivers
In this post we will see how to access data of the Host Web. We will perform two tasks:
  1. Read the title of the Host Web
  2. Create a list in Host Web.
Open the Default.aspx page and add following code to it:

<div>
        <button id="getHostWebTitle">Get Host Web title</button>
</div>
Now open the app.js file. Here, we will attach a click event with the button and execute the code to get the Title of Host Web. Declare a global variable on top of the file.
var hostweb;
Add the below code inside document.ready function.
$("#getHostWebTitle").click(function (event) {
         getHostWebProperties();
         event.preventDefault();
         });
Finally, add the following functions to the .js file:
function getHostWebProperties()
    {
        var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
        var currentcontext = new SP.ClientContext.get_current();
        var hostcontext = new SP.AppContextSite(currentcontext, hostUrl);
        var hostweb = hostcontext.get_web();
        currentcontext.load(hostweb, "Title");
        currentcontext.executeQueryAsync(onGetWebSuccess, onGetWebFail);
    }

function getQueryStringParameter(param) {
    var params = document.URL.split("?")[1].split("&");    
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == param) {
            return singleParam[1];
    }   
    }
    }

function onGetWebSuccess() {
        alert("The title of the host web of this app is " + hostweb.get_title());
    }

function onGetWebFail(sender, args) {
        alert('Failed to get host web title. Error:' + args.get_message());
    }
AppContextSite object needs to be used in order to work with Host web. It takes two parameters, the context of the current site i.e App Web and url of the Host Web. The Url of the Host Web is obtained by reading the value of "SPHostUrl" token. Please visit MSDN link for a complete list of tokens available in SharePoint 2013 apps. Lastly, we need to give the app Read permissions on the Host Web site. This can be done by going into App properties -> Permissions -> Content -> Web.

Read Permissions on Web

Run the application and Trust it. Click on the "Get Host Web Title" button to get the Title of Host Web as shown:

Host Web Title

Now, we will see how to create a list in Host Web. Add the following code in the Default.aspx page:
<div>
    <input type="text" value="Enter List Name" id="createList"/>
    <button id="createListInHostWeb">Create List In Host Web</button>
</div>
The name of the list will be entered in the textbox and a lsit will be created on click of the button.
Add the following code in the document.ready function:
$("#createListInHostWeb").click(function (event) {
        createlist();
        event.preventDefault();
    });
Add the following functions for creating a list of type Announcements in the Host Web.
function createlist() {
        // Create an announcement SharePoint list with the name that the user specifies.
        var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
        var currentcontext = new SP.ClientContext.get_current();
        var hostcontext = new SP.AppContextSite(currentcontext, hostUrl);
        var hostweb = hostcontext.get_web();
        var listCreationInfo = new SP.ListCreationInformation();
        var listTitle = document.getElementById("createList").value;
        listCreationInfo.set_title(listTitle);
        listCreationInfo.set_templateType(SP.ListTemplateType.announcements);
        var lists = hostweb.get_lists();
        var newList = lists.add(listCreationInfo);
        context.load(newList);
        context.executeQueryAsync(onListCreationSuccess, onListCreationFail);
    }

    function onListCreationSuccess() {
        alert('List created successfully!');
    }

    function onListCreationFail(sender, args) {
        alert('Failed to create the list. ' + args.get_message());
    }
Lastly, we need to give Manage permissions to the app so that it can create a list in Host Web.

Manage Permissions

Run the application, it will ask if you trust the application. The application is going to create/delete lists on the Host Web. 

Trust It

Enter the name of the list in textbox and click on Create List In Host Web.

List Created

Browse to the Host Web and locate your list.

Announcements List

profile for Nadeem Yousuf at SharePoint Stack Exchange, Q&A for SharePoint enthusiasts

+