0

I tried retrieving List items from the List(Marketplace) I created in the Hostweb using REST services in NAPA app , Set the permissions for Web, Site Collection, List to Full Control, Please helpe me what is blocking me!! I see that the Error code is executing, I tried adding alert in SuccessHandler but it doesn't show.. Any Help is appreciated

Code in App.js :

'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var hostweburl;
var appweburl;

(function () {

// This code runs when the DOM is ready and creates a context object which is 
// needed to use the SharePoint object model
$(document).ready(function () {
    getUserName();
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl  = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    var scriptbase = hostweburl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js", getlistitems);
});
 function getQueryStringParameter(paramToRetrieve) 
 {
var params = document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) 
  {
    var singleParam = params[i].split("=");
    if (singleParam[0] == paramToRetrieve)
           return singleParam[1];
      }
  }

  function getlistitems() 
  {
    // executor: The RequestExecutor object
    // Initialize the RequestExecutor with the app web URL.
    var executor = new SP.RequestExecutor(appweburl);

// Issue the call against the app web.
// To get the title using REST we can hit the endpoint:
//      appweburl/_api/web/lists/getbytitle('listname')/items
// The response formats the data in the JSON format.
// The functions successHandler and errorHandler attend the
//      sucess and error events respectively.
executor.executeAsync(
    {
        url:
            appweburl +
            "/_api/web/lists/getbytitle('Marketplace')/items",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: successHandler,
        error: errorHandler
    });

}

// Function to handle the success event.
// Prints the data to the page.
  function successHandler(data) 
   {

var jsonObject = JSON.parse(data.body);
var marketplaceHTML = "";
var results = jsonObject.d.results;

for (var i = 0; i < results.length; i++) 
  {
    marketplaceHTML = marketplaceHTML + "<p><h1>" + results[i].Title + "</h1>" +   results[i].Description + "</p><hr>";
      }

document.getElementById("renderMarketplace").innerHTML = marketplaceHTML;

   }

// Function to handle the error event.
// Prints the error message to the page.
  function errorHandler(data, errorCode, errorMessage) 
   {
    document.getElementById("renderMarketplace").innerText = "Could not complete cross-domain call: " + errorMessage;
   }



// This function prepares, loads, and then executes a SharePoint query to get 
// the current users information
function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.get_title());
}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}

})();

Code in Default.aspx

I have just added the below Div with ID "renderMarketplace"

<div>
    <p id="message">
        <!-- The following content will be replaced with the user name when you run the app - see App.js -->
        initializing...
    </p>
</div>
<div id="renderMarketplace"></div>

Error I get:

enter image description here

  • Have you added in the listname var to Nadeem's code which is correct. Also check the name of your list. S – Stephen Jan 28 '14 at 15:19
  • I passed List name as below, I don't think I need to attach the listname to a variable and call it in my function url: appweburl + "/_api/web/lists/getbytitle('Marketplace')/items", – kart Jan 28 '14 at 15:55
  • Well in Nadeem's code yes you do. The error you got was saying that the list was not found... – Stephen Jan 28 '14 at 16:02
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – Waqas Sarwar MVP Jan 10 '15 at 17:31
4
// READ opperation
// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in.
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function getListItems(listName, siteurl, success, failure) {
    $.ajax({
        url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

// CREATE Operation
// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. // title: The value of the title field for the new item
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function createListItemWithDetails(listName, siteUrl, title, success, failure) {

    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "Title": title
    };

    $.ajax({
        url: siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

Taken from http://blogs.msdn.com/b/uksharepoint/archive/2013/02/22/manipulating-list-items-in-sharepoint-hosted-apps-using-the-rest-api.aspx

Following post will show you how to create an app using NAPA and client object model. You can replace the client object code and use REST http://sharepointnadeem.blogspot.com/2013/12/sharepoint-2013-develop-sharepoint-2013.html

  • The answer of Nadeem in above is right for your situation and you can refer here for completely basic operations using Sharepoint 2013 RESTs endpoint. http://msdn.microsoft.com/en-us/library/jj164022.aspx – MikeTran13 Jan 24 '14 at 7:48
  • Nadeem - Thanks for your help, it really helped me understand how it goes.But Apologies!! I am trying NAPA app with JSOM and REST services for first time... I made edits to the above question... Let me know if I am doing anything wrong here – kart Jan 28 '14 at 14:47
  • Mike- Appreciate your help, i have tried the above way.. let me know if I am missing anything – kart Jan 28 '14 at 14:49
  • 1
    You need to use AppContextSite(@target) when constructing a list url of the host web in REST. See this example: cann0nf0dder.wordpress.com/2013/04/14/… – Nadeem Yousuf Jan 28 '14 at 15:19
  • I added the same but i get the same error.. What Should be @target? – kart Jan 28 '14 at 15:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.