locked
Cross Domain Call RRS feed

  • Question

  • Dear Community,

    The function in bold is called on button click, I would like to convert this to cross domain call. however, executor.executeAsync function is not getting executed at all. Can you please assist?

    var hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    var appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

    function CheckClipAmount()
    {
    // Get the Plant
    var sPlant = NWF$('#' + varddlPlant + ' option:selected').text();
    if (sPlant == 'Please select a value...')
    {
    alert ('Please select a Plant.');
    return;
    }

    // Get the Amount
    var sAmount = NWF$("#" + varlaTotalValue).val();

    // Get the GOA Message
    var sGOAMessage = 'GOA not required';
    var url;


    /*
    url = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('ClipLevels')/items?$select=Message&$filter=(Title eq '" + sPlant + "' and MinAmount le " + sAmount + " and MaxAmount gt " + sAmount + ")";
    var call = NWF$.ajax(
    {
    url: url,
    type: "GET",
    async: false,
    dataType: "json",
    headers: { Accept: "application/json;odata=verbose" }
    }); 

    call.done(function (data, textStatus, jqXHR) 
    {
    if (data.d.results[0])
    {
    var rtDATA = data.d.results[0].Message;
    sGOAMessage = rtDATA;
    }
    }); 

    call.fail(function (jqXHR, textStatus, errorThrown) 
    {
    alert("Error Getting Active Data: " + jqXHR.responseText);
    return;
    });
    */

    var hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
        var appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
        var deferred = NWF$.Deferred();
    try{
    var subStrUrl2="&@target='" + hostweburl + "'";
    var executor = new SP.RequestExecutor(appweburl);
    var url=appweburl+"/_api/SP.AppContextSite(@target)/web/lists/GetByTitle('ClipLevels')/Items?$select=Message&$filter=(Title eq '" + sPlant + "' and MinAmount le " + sAmount + " and MaxAmount gt " + sAmount + ")"+subStrUrl2;
            
    executor.executeAsync(
                 {
    url: url,
                     method: "GET",
                     headers: { "accept": "application/json;odata=verbose" },
    success: function (data) {
    var jsonobj = JSON.parse(data.body);
                         var results = jsonobj.d.results;
                         if (results.length == 0) {
                            //var rtDATA = data.d.results[0].Message;
                //sGOAMessage = rtDATA;
    alert(data.d.results[0].Message);
                         }
    else{
    for(var u=0;u<results.length;u++){

    }
    }  
     
    },
    error: function (sender, args) {
                alert('Error Getting Active Data: ' + args.get_message());
    deferred.reject(data);
            }
    });
    }
    catch (error) {
            alert('Error Getting Active Data:' + args.get_message());
    deferred.reject(data);
            
        }


    // Display the GOA Message
    alert('For Plant \'' + sPlant + '\' and Amount \'' + sAmount + '\' the GOA Message is:\n\n' + sGOAMessage);
    return deferred.promise();
    }


    Best Reagards


    • Edited by wiki_vk Monday, July 6, 2020 11:57 AM
    Monday, July 6, 2020 11:57 AM

All replies

  • Hi wiki_vk,

    Before using Cross Domain Library, it's necessary to load SP.RequestExecutor.js using $.getScript, here is a working code demo to use Cross Domain Library:

    App.js:

    'use strict';
    
    //global variables.
    var hostwebUrl
    var appwebUrl;
    var web;
    // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
    /*Get the page ready*/
    $(document).ready(function () {
        hostwebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
        appwebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
        var scriptbase = hostwebUrl + "/_layouts/15/";
        $.getScript(scriptbase + "SP.RequestExecutor.js");
    });
    
    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 getTitleXd() {
        execCrossDomainTitleRequest();
    }
    //Cross Domain Call to obtain HostWeb Title.
    function execCrossDomainTitleRequest() {
        var executor;
        executor = new SP.RequestExecutor(appwebUrl);
        var url = appwebUrl + "/_api/SP.AppContextSite(@target)/web/Title?@target='" + hostwebUrl + "'";
        executor.executeAsync({
            url: url,
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: successTitleHandlerXD,
            error: errorTitleHandlerXD
        }
        );
    }
    //Success Title
    function successTitleHandlerXD(data) {
        var jsonObject = JSON.parse(data.body);
        $('#lblResultTitle').html("<b>Via Cross Domain the title is:</b> " + jsonObject.d.Title);
    }
    //Error with Title.
    function errorTitleHandlerXD(data, errorCode, errorMessage) {
        $('#lblResultTitle').html("Could not complete cross-domain call: " + errorMessage);
    }
    
    /*Button Click Get Lists Cross Domain*/
    function getListsXd() { execCrossDomainListRequest(); }
    //Cross Domain Call to obtain Host Web Lists
    function execCrossDomainListRequest() {
        var executor;
        executor = new SP.RequestExecutor(appwebUrl);
        var url = appwebUrl + "/_api/SP.AppContextSite(@target)/web/lists?@target='" + hostwebUrl + "'";
        executor.executeAsync({
            url: url,
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: successListHandlerXD,
            error: errorListHandlerXD
        });
    }
    //Success Lists
    function successListHandlerXD(data) {
        var jsonObject = JSON.parse(data.body);
        //Get LIsts
        var lists = jsonObject.d.results;
        $('#lblResultLists').html("<b > Via Cross Domain the lists are:</b > ");
        //Loop through each item adding to the label.
        var listsHtml = $.each(lists, function (index, list) {
            $('#lblResultLists').append(list.Title + " (" + list.ItemCount + ")"+"<br/>");
        });
    }
    //Error Lists
    function errorListHandlerXD(data, errorCode, errorMessage) {
        $('#lblResultLists').html("Could not complete cross-domain call: " + errorMessage);
    }

    Default.aspx:

    <%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>
    
    <%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>
    
    <%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    
    <%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
    <asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
        <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
        <SharePoint:ScriptLink name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
        <meta name="WebPartPageExpansion" content="full" />
    
        <!-- Add your CSS styles to the following file -->
        <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
    
        <!-- Add your JavaScript to the following file -->
        <script type="text/javascript" src="../Scripts/App.js"></script>
    </asp:Content>
    
    <%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
    <asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
        Page Title
    </asp:Content>
    
    <%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
    <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    
    <div>
    <h2>Please select a way to bring back the title from the host web:</h2>
    </div>
    <div><input id="btnCrossDomainGetTitle" onclick="getTitleXd()" type="button" value="Get Title via REST Cross Domain" /></div>
    <div>
    <h2>Please select a way to bring back all lists in the host web:</h2>
    </div>
    <div><input id="btnCrossDomainGetLists" onclick="getListsXd()" type="button" value="Get Lists via REST Cross Domain" /></div>
    <div id="lblResultTitle"></div>
    <div id="lblResultLists"></div>
    
    </asp:Content>

    AppManifest.xml:

    Result:

    Reference:

    Cross Domain and SharePoint Hosted Apps using REST


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.



    Tuesday, July 7, 2020 6:34 AM
  • Hello Jerry Zy,

    I am using this code on Nintex office 365 button click. Would the solution given also work the same way? We don't have Appmanifest.xml there? what changes do I need to make if this is the case?  Appreciate your help.




    • Edited by wiki_vk Tuesday, July 7, 2020 7:18 AM
    Tuesday, July 7, 2020 7:18 AM
  • Hi wiki_vk,

    Are you writing the code in SharePoint hosted add-in ?

    I see you are getting appweburl and hostweburl in your cvode snippet.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Tuesday, July 7, 2020 7:23 AM
  • Hi Jerry, the commented piece of code is what exists in on-premise and this needs to work in office 365 as well. So I added the appweburl and hostweburl.  When I debugged, I saw it has URL that contains appweburl and hostweburl 



    • Edited by wiki_vk Tuesday, July 7, 2020 7:51 AM
    Tuesday, July 7, 2020 7:51 AM
  • Hi wiki_vk,

    I understand your situation now.

    The commented Rest API is the normal Rest call and now you want to use it in SharePoint Online.

    For this concern, you can still use the normal Rest Call in SharePoint Online classic page, no need to convert into the Cross Domain version.

    Cross Domain Library mainly used in SharePoint hosted add in with AppManifest.xml, if you don't have AppManifest.xml, I assume you are not build the SharePoint hosted add in solution.

    You can add the commented Rest call using Script Editor Web Part directly, here is a video demo for your reference:

    Script Editor Web Part in SharePoint Online or SharePoint 2013/2016/2019

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Tuesday, July 7, 2020 8:06 AM
  • Hello Jerry Zy,

    I troed commented code earlier. Its confusing as below guide says Nintex is a provider hosted app. 

    https://community.nintex.com/t5/Nintex-for-Office-365/Access-SharePoint-Lists-REST-API-from-Nintex-for-Office-365/td-p/54304




    • Edited by wiki_vk Tuesday, July 7, 2020 8:17 AM
    Tuesday, July 7, 2020 8:17 AM
  • Hi wiki_vk,

    I have less knowledge about Nintex Form as it's a third party paid Platform.

    But if you only want to use the commented Rest call in SharePoint Online, no need to use Nintext or any Add-in (SharePoint Hosted/Provider Hosted).

    Just add the JavaScript code into Script Editor Web Part like the video guided above will do the trick.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Tuesday, July 7, 2020 8:23 AM