SharePoint hosted app part and SPHostUrl + SPAppWebUrl

Hi,
I have sharepoint hosted app that gets hostweburl and appweburl with the next lines 
function getUrl() {
hostweburl = getQueryStringParameter("SPHostUrl");
appweburl = getQueryStringParameter("SPAppWebUrl");
hostweburl = decodeURIComponent(hostweburl);
appweburl = decodeURIComponent(appweburl);
var scriptbase = hostweburl + "/_layouts/15/";
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js",
function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execOperation); }
function execOperation() {
context = new SP.ClientContext(appweburl);
appContextSite = new SP.AppContextSite(context, hostweburl);
And this works fine. But when I'm creating app part those hostweburl and appweburl fields are undefined. So I cant get the context and everything is broken. Is this done in some other way in app parts? 

Like this in the ClientWebPart   
<Content
      Type="html"
      Src="~appWebUrl/Pages/Welcome.aspx?{StandardTokens}&amp;ShowImage=_ShowImage_" />
The {StandardTokens} contains all the queryString parameters you need.
Author,
Microsoft SharePoint 2013 App Development
Author,
Professional Business Connectivity Services
Author,
Inside SharePoint 2013
Blog, www.shillier.com
Twitter, @ScotHillier
SharePoint Trainer, Critical Path Training

Similar Messages

  • How to get IdP Token (SAML Response) in Office 365 using SharePoint hosted app parts.

    Hi All
    We have a requirement to retrieve data from SQl azure & consume it O365 Sharepoint hosted app parts. to expose SQL azure data we implemented Web API .  Now we are struck at securing Web API. I found below flow in internet search.
    In this process
    Client component (App part) get  IdP token ( signed SAML Responce) from sharepoint & sends IdP token to ACS, which validates the token signature & claims & issues Access Token(valid for 600sec) to client ,which would be forwarded to
    Web API. where web Api validates & provides data.
    Client - SharePoint Site (App parts)
    Identity provider : Onelogin is our Identity provider.
    Application : Web API
    In this whole process . how to get IdP Token (SAML Response) from sharepoint in Sharepoint hosted appparts using client object model? 
    can any one help on this.
    ragava_28

    Hi,
    According to your post, my understanding is that you want to enable/disable the custom ribbon button accordingly.
    We can use the EnabledScript attributes to achieve this scenario.
    The EnabledScript attribute of the CommandUIHandler that will enable or disable the button depending on whether the function returns true or false. 
    There are some articles about this topic, you can refer to them.
    http://dannyjessee.com/blog/index.php/2013/01/javascript-to-conditionally-enable-a-sharepoint-custom-ribbon-button/
    http://aaclage.blogspot.com/2014/07/how-to-enabledisable-ribbon-buttons-by.html
    http://dannyjessee.com/blog/index.php/2014/06/enabling-custom-ribbon-buttons-dynamically-based-on-multiple-selected-item-values-using-refreshcommandui-and-jsom/
    Thanks,
    Jason
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Jason Guo
    TechNet Community Support

  • How to get inputted value in a RTE field on custom page and submit by REST call in 'Sharepoint hosted app'.

    Hi I am facing the three questions below.
    1. How to use default RTE in custom page in Sharepoint hosted app.
     I saw the article of Rich text Editor (ribbon based) in a webpart in SharePoint 2013 and tried it. But it did not work well. I guess it needs code-behind setting, however sharepoint hosted app does not support code-behind.
    Does anybody know how to do this?
    2. In above case, I placed the below code on custom page and tried to get the field's value when submit button was clicked.
    <SharePoint:InputFormTextBox ID="rftDefaultValue"
    RichText="true"
    RichTextMode="FullHtml" runat="server"
    TextMode="MultiLine" Rows="5">
    </SharePoint:InputFormTextBox>
    In debugger, the returned value was 'undefined'.
    var note = $('#hogehoge').val();
    Is it possible to get the RTE value? If yes, please let me know how to do this.
    3. I need to submit the RTE value using REST call.
    In this
    article in MSDN, the item creation sample treats single line text field. Does anybody know the sample for RTE?

    Hi,
    According to your description, you might want to use Rich Text Editor control in your SharePoint hosted app.
    First of all, I would suggest you post one question in one thread to make it easier to be discussed, which would also help you get a quick solution.
    Though we can add this control into a SharePoint hosted app, however, as we can’t add code behind for it, plus with the potential compatibility issues in different
    browsers, I would suggest you use other JavaScript Rich Text Editor plugins instead.
    Two JavaScript Rich Text Editor plugins for your reference:
    http://quilljs.com/
    http://nicedit.com/
    If you want to submit the value of Rich Text Editor control to a SharePoint list using REST call, since the content in the Multiple Line of Text column is wrapped
    with nested HTML tags, the similar requirement would also be applied to the content to be submitted.
    Here is a code snippet about how to update a Multiple Line of Text column for your reference:
    updateListItem(_spPageContextInfo.webAbsoluteUrl, "List018", 1);
    function updateListItem(siteUrl, listName, itemId)
    var itemType = GetItemTypeForListName(listName);
    var item = {
    "__metadata": { "type": itemType },
    "MultiTextEnhanced": "<div><a href='http://bing.com/'>Bing</a><br></p></div>",
    "Title": "123"
    $.ajax({
    url: siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + itemId + ")",
    method: "GET",
    headers: { "Accept": "application/json; odata=verbose" },
    success: function (data) {
    console.log(data);
    $.ajax({
    url: data.d.__metadata.uri,
    type: "POST",
    contentType: "application/json;odata=verbose",
    data: JSON.stringify(item),
    headers: {
    "Accept": "application/json;odata=verbose",
    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
    "X-HTTP-Method": "MERGE",
    "If-Match": data.d.__metadata.etag
    success: function (data) {
    console.log(data);
    error: function (data) {
    console.log(data);
    error: function (data) {
    console.log(data);
    // Getting the item type for the list
    function GetItemTypeForListName(name)
    return"SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
    Thanks
    Patrick Liang
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support,
    contact [email protected]
    Patrick Liang
    TechNet Community Support

  • Unable to add aspx file to document library using REST and JSOM in SharePoint Hosted App

    Hi,
    I am unable to add an aspx file to document library.  I was actually trying to create a WIKI page and upload to Pages library but that wasn't working so I tried simple document library.  It keeps failing with Access Denied error.  I have checked
    the blocked types and aspx is not included.  I can upload it directly from the browser so that shouldn't be the case.  I have read that it can be achieved with CSOM but I need this to work with a SharePoint Hosted App.  Here is my JSOM:
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
        context.set_webRequestExecutorFactory(factory);
        appContextSite = new SP.AppContextSite(context, hostweburl);
        oWeb = appContextSite.get_web();
        oList = oWeb.get_lists().getByTitle('Documents');
        fileCreateInfo = new SP.FileCreationInformation();
        fileCreateInfo.set_url("mywiki.aspx");
        fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
        fileContent = "<%@ Page Inherits=\"Microsoft.SharePoint.Publishing.TemplateRedirectionPage,Microsoft.SharePoint.Publishing,Version=15.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c\" %> <%@ Reference VirtualPath=\"~TemplatePageUrl\"
    %> <%@ Reference VirtualPath=\"~masterurl/custom.master\" %>";
        for (var i = 0; i < fileContent.length; i++) {
            fileCreateInfo.get_content().append(fileContent.charCodeAt(i));
        newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);
        context.load(newFile);
        context.executeQueryAsync(function () {
            alert('yo');
        }, function (sender, args) {
            alert(args.get_message() + '\n' + args.get_stackTrace());
    If I change the file extension to "txt", it works.  Same with REST implementation, it works with "txt" but fails with "aspx".  Maybe what I am trying to do will not work using JSOM or REST.  Any suggestions?  Your
    help is always appreciated.
    Regards,
    kashif

    Your code works fine in both my on-premises and SharePoint Online. I have given the app full control, so I suspect this is a permissions issue. I would check your permissions on your appmanifest. Must be something to do with publishing permissions. Try
    giving full control and work the permissions down.
    Blog | SharePoint Field Notes Dev Tools |
    SPFastDeploy | SPRemoteAPIExplorer

  • SharePoint hosted App that listens and log SharePoint Events

    Basically, what I need, is something that can listen to all events fired in SharePoint and write them to a custom list.
    I was thinking of making this as a SharePoint hosted app because it has to work on SP Online as well.
    The idea is then, to let a provider hosted app read the custom list every x minutes and do it's own logic depending on the events it reads from the custom list.
    So the question is, how do I catch all the events fired in SharePoint and should it be a SharePoint hosted app that does it?
    Any thoughts on how to solve this?
    Thanks.
    Thomas Bomann, simplySo

    Hi,
    According to your description, my understanding is that you want to track all the event fired in SharePoint .
    Listen to the events in SharePoint needs Server side code, see the article below:
    Programming Event Handling in Windows SharePoint Services
    In SharePoint hosted app, it needs to use Client Object Model, so there is no such Client API to meet the requirement.
    More information:
    JavaScript Client Object Model in SharePoint 2013
    Thanks
    Best Regards,
    Jerry Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

  • Sharepoint-Hosted App giving FORBIDDEN error when i use REST Api

    Hi,
    I have created a sharepoint hosted app which will create Team site on button click.
    I used REST Api  and  NAPA Tool to develop this app.
    Napa tool gives to things ClientWebpart.aspx and Default.aspx.
    When i run my Default.aspx code is working fine but ClientWebpart.aspx is giving FORBIDDEN error when i am trying to create site.
    Below is the code which i used to create site
    code:
    var hostweburl;
    var appweburl;
    $(document).ready(function () {
    hostweburl= decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    function createSPWeb() {
    $.ajax(
    url: appweburl +
    "/_api/SP.AppContextSite(@target)/web/webinfos/add?@target='" +
    hostweburl + "'",
    type: "POST",
    data: JSON.stringify(
    'parameters':
    '__metadata': { 'type': 'SP.WebInfoCreationInformation' },
    'Url': 'RestSubWeb',
    'Title': 'RestSubWeb',
    'Description': 'REST created web',
    'Language': 1033,
    'WebTemplate': 'sts#0',
    'UseUniquePermissions': false
    headers: {
    "accept": "application/json;odata=verbose",
    "content-type": "application/json;odata=verbose",
    "X-RequestDigest": $("#__REQUESTDIGEST").val()
    success: successHandler,
    error: errorHandler
    NOTE:This is on sharepoint online.
    Please help
    Regards,
    sudeep

    So in the app you are testing, are you using the FQDN or the NetBIOS name? Bad practice but could you test with both (hard code the absolute URL for testing purposes) then retest your app?
    If you are making a web part based on the new app model this will be an "app part" and probably have the same issues you are experiencing. If this is for something internal rather than a product you are developing to resell then the script editor /
    content editor web part approach could work for you.
    Paul
    Paul Mather | Twitter |
    http://pwmather.wordpress.com | CPS

  • SP is undefined in sharepoint hosted app client Webpart

    Hello All,
    For a client web part in sharepoint hosted app, I am getting the following error
    "SP is undefined".
    My code is bel0w
       <script
     type="text/javascript"
     src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js">
    </script>
        <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
         <script  type="text/javascript" src="/_layouts/sp.core.js"></script>
        <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
            <script type="text/javascript" src="/_layouts/15/sp.js"></script>
        <script type="text/javascript">
            'use strict';
            $(document).ready(function () {
                        ExecuteOrDelayUntilScriptLoaded(loadConstants, "sp.js");
                    var  clientContext = SP.ClientContext.get_current();
                   var  web = clientContext.get_web();
    </script>     ....
    I am getting the error ExecuteOrDelayUntilScriptLoaded is undefied. This script is in client Web part
    Any help is appreciated.
    Vishnu

    Thanks for the reply Geetanjali.
    var  clientContext = SP.ClientContext.get_current();
     var  web = clientContext.get_web();
    These two lines of code is supposed to be inside "loadConstants" method.
    After changing the code as below, I am able to get SPClientContext and SPWeb.Also, host and appweb url as well
    <script
    type="text/javascript"
    src="../Scripts/jquery-1.6.2.min.js"></script>
     <script
    type="text/javascript"
    src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
     <script
    type="text/javascript"
    src="../Scripts/App.js"></script>
    $(document).ready(
        function () {
    var spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
          var appWebUrl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
    var layoutsRoot = spHostUrl + '/_layouts/15/';
            $.getScript(layoutsRoot +
    "SP.Runtime.js",
    function () {
                $.getScript(layoutsRoot +
    "SP.js", loadConstants);
    function loadConstants() {
                context =
    new SP.ClientContext.get_current();
                web = context.get_web();
    Thanks
    Vishnu
    dfd

  • __REQUESTDIGEST is undefined in sharepoint hosted app ( Client WebPart ) but its working in full page app

    I have found the answer in below url. but howerver i am not sure from where the "accessToken" coming.
    Any idea?
    http://social.msdn.microsoft.com/forums/windowsapps/en-us/816291e7-8081-46e0-8ec3-e67613d1621f/requestdigest-is-undefined-in-sharepoint-hosted-app?forum=appsforsharepoint
    Navaneeth

    Okay. Finally i found solution after 2 weeks :)
    Below is the way to use. Note its working in both Single Page App and Client App Part as well
    var formDigest; //Declare the variable
    //Document Ready
    $(document).ready(function () {
        hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
        appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
        scriptbase = hostweburl + '/_layouts/15/';
        CharacterAnimation();
        $.getScript(scriptbase + 'SP.Runtime.js', function ()
            $.getScript(scriptbase + 'SP.js', function ()
                $.getScript(scriptbase + 'SP.RequestExecutor.js', getFormDigest);
    //Get  Form Digest Value
    function getFormDigest() {
        var appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
        $.ajax({
            url: appweburl + "/_api/contextinfo",
            type: "POST",
            headers: {
                "accept": "application/json;odata=verbose",
                "contentType": "text/xml"
            success: function (data) {
                requestdigest = data;
                var formDigest = data.d.GetContextWebInformation.FormDigestValue;
                DoSomething(formDigest);
            error: function (err) {
                alert(JSON.stringify(err));
    //Do Something Method
    function  DoSomething(formDigest) {
    var urltest = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getByTitle('List1')/getitems(query=@v1)?@v1={\"ViewXml\":\"<View><Query><Where><BeginsWith><FieldRef Name='Title'/><Value Type='Text'>A</Value></BeginsWith></Where></Query><RowLimit>1</RowLimit></View>\"}&@target='"
    + hostweburl + "'";
            $.ajax({
            url: urltest,
            type: "POST",
            headers: {
                "Accept": "application/json; odata=verbose",
                "Content-Type": "application/json; odata=verbose",
                "X-RequestDigest": formDigest
            contentType: 'application/json',
            success: function (data) {
                alert(data); // Finally found [Object][Object] :)
            error: function (data) {
                alert(data.responseText);
    Navaneeth

  • How to get hostweb's site collection in SharePoint hosted app?

    I want display SharePoint site collection of host web in my SharePoint hosted app. I have used following code. 
    ExecuteOrDelayUntilScriptLoaded(callSharePoint, "sp.js");
    function callSharePoint() {
    hostweburl = getQueryStringParameter("SPHostUrl");
    appweburl = getQueryStringParameter("SPAppWebUrl");
    hostweburl = decodeURIComponent(hostweburl);
    appweburl = decodeURIComponent(appweburl);
    var scriptbase = appweburl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.Runtime.js",
    function () {
    $.getScript(scriptbase + "SP.js",
    function () {
    //$.getScript(scriptbase + "SP.Taxonomy.js", function () { });
    $.getScript(scriptbase + "SP.RequestExecutor.js", execOperation);
    //Loads context, web and lists....
    function execOperation() {
    try {
    //create context for appweburl.
    context = new SP.ClientContext(appweburl);
    var factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    //get hostsite reference & load as web.
    appContextSite = new SP.AppContextSite(context, hostweburl);
    web = appContextSite.get_web();
    context.load(web);
    list = web.get_lists();
    context.load(list);
    webs = appContextSite.get_web().get_webs();
    context.load(webs);
    //webs = appContextSite.get_site().get_rootWeb().get_webs();
    //context.load(webs);
    context.executeQueryAsync(onWebsLoaded, onQueryFailed);
    catch (err) {
    alert(err.message);
    function onWebsLoaded(sender, args) {
    alert(list.get_count());
    var webEnum = list.getEnumerator();
    while (webEnum.moveNext()) {
    web = webEnum.get_current();
    alert(web.get_id());
    for (var i = 0; i < webs.get_count() ; i++) {
    subwebs = webs.itemAt(i);
    recursiveAll(subwebs);
    /* recursive call for web */
    function recursiveAll(cweb) {
    debugger;
    alert(cweb.get_title());
    var subwebs = cweb.get_webs();
    context.load(subwebs);
    context.executeQueryAsync(function (sender, args) {
    debugger;
    var webEnum = subwebs.getEnumerator();
    while (webEnum.moveNext()) {
    web = webEnum.get_current();
    alert(web.get_title());
    //recursive call for current web.
    recursiveAll(web);
    }, function () { debugger; alert('err'); });
    In this code I have get all the list of the Host web. But I am not able to get Host webs.
    Any of the when I load the Web it gives me the AppWebUrl not the host web.
    So I tried by using following code
    context = new SP.ClientContext(hostweburl);
    web = appContextSite.get_web();
    context.load(web);
    context.executeQueryAsync(onWebsLoaded, onQueryFailed);
    But it gives me error: unexpected response data from server
    Is there any other way to view all sites and sub sites of the host web in SharePoint hosted app?

    Hi,
    Since you are using a provider Hosted app if you want to get the current logged in name than do not use AppOnlyAccessToken else use AccessToken which is App + user Context AccessToken.
    then 
    Web web = clientContext.Web;
    clientContext.Load(web);
    clientContext.ExecuteQuery();
    clientContext.Load(web.CurrentUser);
    clientContext.ExecuteQuery();
    clientContext.Web.CurrentUser.LoginName;will return proper user Name.
    HttpContext.Current.User.Identity.Name will never return the user as this object is related to IIS server of your App Server not sharepoint.you should set this as Anonymous in case of provider hosted app.you can download the below sample which uses the AccessToken which has user name in it.https://code.msdn.microsoft.com/Working-provider-hosted-8fdf2d95
    Whenever you see a reply and if you think is helpful,Vote As Helpful! And whenever you see a reply being an answer to the question of the thread, click Mark As Answer

  • How to open List when Page loads in SharePoint Hosted App?

    I  want to create an app same like InstantPracticeManager by InstantQuick.
    Now I want to know that in a SharePoint Hosted App How can I show the Whole List in a page. 
    Here I have added one image:
    Here there is one list and there are 4 views of that list.
    Now the App will be like when I load the page It will show like the image above. Now how can we show the list like this in sharepoint hosted app?
    I want the same scenario which is shown in the following blogs:
    http://sp2013.blogspot.in/2012/08/use-list-view-in-sharepoint-2013-apps.html
    and
    http://www.sharepointnutsandbolts.com/2013/08/working-with-web-parts-within.html
    where they add a list to an app
    Can any one suggest me the idea? I am bit confused.
    thanks in advance.

    Hi,
    According to your post, my understanding is that you want to show the different list view in a page in SharePoint Hosted App.
    We can use jQuery and cross-domain library to achieve it.
    The following articles for your reference:
    Adding a Tabbed View to A Web Part Page Using jQueryUI
    http://sympmarc.com/2011/11/09/adding-a-tabbed-view-to-a-web-part-page-using-jqueryui/
    How to: Access SharePoint 2013 data from apps using the cross-domain library
    http://msdn.microsoft.com/en-us/library/office/fp179927(v=office.15).aspx
    SharePoint 2013: Get list items by using the cross-domain library (JSOM)
    http://code.msdn.microsoft.com/office/SharePoint-2013-Get-items-d48150ae/view/SourceCode#content
    Thanks,
    Dennis Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Dennis Guo
    TechNet Community Support

  • Need SharePoint Hosted App for Stock quotes.

    Hi All,
    I need a code for SharePoint hosted app wherein I want to show stock quotes of company. This App part should be configurable.
    Specifically Looking for code which developed in NAPA tool. But any help would be greatly appricieated.
    Thanks,
    Dhananjay.

    Hi Dhananjay,
    Please check if below article helps you :
    How to Display Stock Information in SharePoint 2013
    If my contribution helps you, please click Mark As Answer on that post and
    Vote as Helpful
    Thanks, ShankarSingh(MCP)

  • SharePoint Hosted App - Creating cascaded drop down on hosted web lists

    Hi,
    I have created an SharePoint Hosted App(Javascript Object Model) that creates lists on the host web.
    I need to put some javascript into new and edit forms in order to create the cascaded drop down effect on 2 lookup fields.
    Can you please give me some advise?
    Regards,
    Marian

    Hope below article should help you
    http://blog.pentalogic.net/2010/11/editing-the-sharepoint-list-item-menu-part-2-using-javascript/
    http://www.getinthesky.com/2014/03/hide-text-field-sharepoint-form-using-jquery/
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/030471b2-d19a-470f-9a9e-0fd8a229138b/how-do-i-create-a-new-item-form-that-allows-to-save-and-continue-editing?forum=sharepointcustomizationlegacy

  • Unable to update rating (rating column) on host document using JavaScript Object Model API inside sharepoint hosted apps

    Hi Everyone,
    We are developing SharePoint hosted apps for Office 365, for that we are going
    to implement document rating functionality inside Sharepoint app. The host web contain document library (“Documents”) and from apps we need to rate each document. The rating functionality working fine with CQWP in team site  using
    JavaScript Object Model API.
    But the same code is not working inside apps and giving error:-
    If we are using app context than error will be:-
    "List does not exist.
    The page you selected contains a list that does not exist.  It may have been deleted by another user."
    And for Host context than error will be:-
    "Unexpected response data from server."
    Please help on this
    Please see below code..
    'use strict';
    var web, list, listItems, hostUrl, videoId, output = "";
    var videoLibrary = "Documents";
    var context, currentContext;
    var lists, listID;
    var list, parentContext;
    var scriptbase;
    (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 () {
            hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
            context = SP.ClientContext.get_current();      
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);
        function sharePointReady() {
            scriptbase = hostUrl + "/_layouts/15/";
            // Load the js files and continue to the successHandler
            $.getScript(scriptbase + "SP.Runtime.js", function () {
                $.getScript(scriptbase + "SP.js", function () {
                    $.getScript(scriptbase + "SP.Core.js", function () {
                        $.getScript(scriptbase + "reputation.js", function () {
                            $.getScript(scriptbase + "sp.requestexecutor.js", execCrossDomainRequest);
        //Query list from hostweb
        function execCrossDomainRequest() {       
            //Load the list from hostweb
            parentContext = new SP.AppContextSite(context, hostUrl);
            web = parentContext.get_web();
            list = web.get_lists().getByTitle(videoLibrary);
            context.load(list, 'Title', 'Id');
            var camlQuery = new SP.CamlQuery();
            camlQuery.set_viewXml('<View><Query><OrderBy><FieldRef Name="Modified" Ascending="FALSE"/></OrderBy></Query><RowLimit>1</RowLimit></View>');
            listItems = list.getItems(camlQuery);        
            context.load(listItems);
            context.executeQueryAsync(onQuerySucceeded, onQueryFailed);
        //Process the image library
        function onQuerySucceeded() {       
            var lstID = list.get_id();
            var ctx = new SP.ClientContext(hostUrl);       
            var ratingValue = 4;
            EnsureScriptFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function() {      
            Microsoft.Office.Server.ReputationModel.Reputation.setRating(ctx, lstID, 1, ratingValue);       
            ctx.executeQueryAsync(RatingSuccess, RatingFailure);
        function onQueryFailed(sender, args) {
            alert('Failed' + args.get_message());
        function failed(sender, args) {
            alert("failed because:" + args.get_message());
        function RatingSuccess() {
            alert('rating set');
            //displaystar();
        function RatingFailure(sender, args) {
            alert('Rating failed : : ' + args.get_message());
        //Gets the query string paramter
        function getQueryStringParameter(paramToRetrieve) {
            var params;
            params = document.URL.split("?")[1].split("&");
            for (var i = 0; i < params.length; i = i + 1) {
                var singleParam = params[i].split("=");
                if (singleParam[0] == paramToRetrieve) return singleParam[1];
    Thanks & Regards
    Sanjay 
    Thank you in advance! :-)
          

    Hi,
    According to your post, my understanding is that you want to update list column in SharePoint hosted apps using JavaScript Client Object Model.
    Based on the error message, it seems not retrieve the list object in context. I suggest you debug the code step by step using Internet Explorer Developer Tools to
    find the problem.
    Here are some demos about using JavaScript Client Object Model in SharePoint hosted app:
    http://blogs.msdn.com/b/officeapps/archive/2012/09/04/using-the-javascript-object-model-jsom-in-apps-for-sharepoint.aspx
    http://sharepoint.stackexchange.com/questions/55334/how-to-access-list-in-sharepoint-hosted-app
    http://www.dotnetcurry.com/showarticle.aspx?ID=1028
    Best regards
    Zhengyu Guo
    TechNet Community Support

  • Upgrade SharePoint Content Types / Site Columns declaratively in SharePoint hosted apps

    Hi!
    I have a question where I was unable to find any official guidance for. I have created a SharePoint hosted APP where I have multiple site columns and content types (declared in XML). The APP installs and functions just fine. 
    Now I have a requirement to change a site column (Choice field, just add some more choice values). I was able to update the site column but the changes will not be reflected on the list column (I think because there no way to push the changes).
    So is there an "official" way of changing site columns?
    Any help is appreciated!
    Thx!

    msdn -
    How to: Update app web components in SharePoint 2013 :
    We do not support changing the data type of a list or content type field (column) after its initial deployment in any
    circumstance. In particular, do not change the data type of a field as part of an app update (not
    even programmatically). As an alternative, you can add a new field. If the app includes custom item create, edit,
    or view forms; be sure to make corresponding changes in these forms. For example, add UI for the new field and remove UI for the old one. (In a provider-hosted app, you can programmatically move data from the old field to the new one and then delete the old.
    How to: Update apps for SharePoint
    [custom.development]

  • CAML query in Workflow inside sharepoint hosted app

    Hi,
    I am building a sharepoint hosted app for sharepoint online.The app includes a list workflow.One of the activity in the workflow is to query another list within the app web, to get count of items where a condition is met.Can anyone please guide me how this
    can be achieved?
    Thanks!

    Hello Steve,
    Thanks for the Reply
    Following code helped me in creating the Subsite successfully in host web
    Var hostWebUrl;
    Var appWebUrl;
    Var context;
    Var newSubsite;
    function () {
    try
    hostWebUrl = GetQueryString("SPHostUrl");
    appWebUrl = GetQueryString ("SPAppWebUrl");
    var layoutsRoot = hostWebUrl +
    '/_layouts/15/';
    $.getScript(layoutsRoot + "SP.Runtime.js",
    function () {
    $.getScript(layoutsRoot + "SP.js", CreateSubsite);});
    catch(ex)
    alert("message" + ex.message);
    function GetQueryString (name) {
    name = name.replace(/[\[]/,
    "\\\[").replace(/[\]]/,
    var regex =
    new RegExp("[\\?&]"
    + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results ==
    null ?
    "" : decodeURIComponent(results[1].replace(/\+/g,
    // Function to create subsite
    function CreateSubsite () {
    context = new SP.ClientContext(appWebUrl);
    var hostContext =
    new SP.AppContextSite(context, hostWebUrl);
    var webCreateInfo =
    new SP.WebCreationInformation();
    //set values
    webCreateInfo.set_description("New Subsite Created");
    webCreateInfo.set_language(1033);
    webCreateInfo.set_title("NewSubSite");
    webCreateInfo.set_url("SubsiteURL");
    webCreateInfo.set_useSamePermissionsAsParentSite(true);
    webCreateInfo.set_webTemplate("STS#0");
     this.web = hostContext.get_web();
    newSubsite = this.web.get_webs().add(webCreateInfo);
    context.load(newSubsite);
    context.executeQueryAsync(
    Function.createDelegate(this,successHandler),Function.createDelegate(this,errorHandler));
    function successHandler() {
    alert("subsite created successfully");
    function errorHandler(sender, args) {
    alert("Could not complete cross-domain call: " + args.get_message());
    Vishnu

Maybe you are looking for

  • How to find out the total cost of a specific VM

    I've downloaded the usage statistics file from billing section and I could see the data categorized by different type of resources consumed by a virtual machine. Eg. Name ResourceGuid Unit Consumed "Virtual Machines" "1b4d8861-8cbc-40c8-88f9-e1b78509

  • Function Module/BAPI for Posting with Residual Clearing

    Hello All, I want to know whether any Function Module/BAPI avaialble for posting with residual clearing (FB05). Can we do residual clearing using the FM "Posting_Interface_Clearing"? Please let me know how this can be handled. Thanks in advance. With

  • How to manually add rows to DataSet ?

    Hi, Apologies if I have missed something obvious - but how should I manually add rows to an empty dataset ? I've seen the setDataFromArray example in the samples - but I just want to take a value from a form field and add it to the dataset. Thanks, R

  • Flash builder 4.0 load xml file for elixir

    Hi,    I am using flash builder 4.0 for creating chart through ibm elixir tool. Now i want give input as xml format or .xlsformat in runtime. How i can give it, Give me some example regards this Regards, sivabharathi

  • Error updating Process Form: Same Column exist with a different variant

    Hi All, I have a process form of a resource with following fields : Name VariantType Length FieldLabel FieldType Order UD_EDIR_BWUSER   boolean       1          BWUser    Checkbox      25 UD_EDIR_ISUUser    boolean       1          ISUUser    Checkbo