0

I am trying to get some data from a REST Service Url in a html file. This works fine when i am using the code direct in my browser. But when i embedded it into my SharePoint Site it wont work.

On my SharePoint Site i have disable MDS (Minimal Download Strategy).

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">

    var getdata = function() {
            $.ajax({
                url: "http://resturl:8080/api/v2/table/_table/v_name?api_key=2e02708088e54b560b33dbcb1e13b7e1488907534262b319d86b58c480fea54c",
                type: "GET",
                async: false,
                headers: {
                    "accept": "application/json;odata=verbose"
                },
            }).success(function (data) {
                    alert("got data");
            });
    }
    var chartdata = getdata();

    </script>
    </head>
<body>
    <h1>Some Text</h1>
</body>

For receiving this data i have to add the api_key to the url or the request.

The response code will be a json format, here a snippet:

{"resource":[{"id":22611},{"id":22649}],"meta":{"count":2661,"next":1000}}

Can anyone tell me why i am get no data when i using this html file out of sharepoint. The authorization should come with the api_key ?!

I also tried this code (because for json support in internet explorer etc.)

jQuery.support.cors = true;
jQuery.getJSON('http://resturl:8080/api/v2/table/_table/v_name?api_key=2e02708088e54b560b33dbcb1e13b7e1488907534262b319d86b58c480fea54c', 
    function(data) {
        alert("yeah");
    }
)
.error(function(jqXHR, textStatus, errorThrown) { alert(errorThrown); });

Thanks for any help.

1
  • Check the Xhr response for your call in the Network tab of F12 Developer tools. If there is no call at all your problem is nopt with the ajax call Commented May 31, 2016 at 8:44

1 Answer 1

4

Actually haven't had my coffee jet and read your question like you needed help with MDS - if you wan't to enable MDS again (which you should do because it's actually awesome), below are some hints that will help you.

Some troubleshooting help for your problem:

  • Check your browsers console for errors
  • Access the service via the URL directly (via browser for example)
  • Check if your code is present on the page (sometimes SP removes elements which are not compliant with its rules
  • Debug your code via the F12 Browser Dev Tools

Here are 2 things to keep in mind when working with MDS:

1. Protect your (and your libraries) NameSpace

MDS is cleaning the window object on every MDS-Navigation. This will cause your global values to get cleaned by their garbage collector.

You can Protect a namespace like this:

// for libraries
// 1. Ensure the library has defined its global objects
// 2. Call this code
if (window.Function != 'undefined' && typeof (Function.registerNamespace) == 'function') {
        Function.registerNamespace('jQuery');
        Function.registerNamespace('$'); 
        Function.registerNamespace('etc'); 
    }

// for your code
// use an IIFE to create a scope and dont dirty the global scope
(function (_) {
    // _ is our object we use to put our code in
    // use strict to ensure we dont code stupid
    'use strict';

    // implement your code like this
    var yourFunctionPublic = function () {
        //code
        console.log('yourFunctionPublic');
        //you can call internal code here
        yourFunctionInternal();
    };

    var yourFunctionInternal = function () {
        //code
        console.log('yourFunctionInternal');
    };

    // every function / variable that should be callable from public you have to publish like below
    _.YourFunction = yourFunctionPublic;

    // attach our object at the namespace we want (this should be unique)
    // THIS WILL PROTECT YOUR GLOBAL VAR FROM THE GARBAGE COLLECTOR
    window.YourNameSpace = _;
    // protect our namespace by registering it
    // this must be done after defining the target object
    if (window.Function != 'undefined' && typeof (Function.registerNamespace) == 'function') {
        Function.registerNamespace('YourNameSpace');            
    }
})({});

// call your public functions / variables 

window.YourNameSpace.YourFunction();

2. Attach to the MDS-Lifecycle

Since you don't have a true reload, you won't have new events (load, etc). If you want your code to run after a navigation (even a MDS one), here's a little utility and how you can attach with it(the last lines show how):

//use an IIFE to create a scope and dont dirty the global scope
(function (_) {
    // use strict to ensure we dont code stupid
    'use strict';

    var initHandlers = [];
    var initMDSHandlers = [];

    var ensureSharePoint = function (handler) {
        var sodLoaded = typeof (_v_dictSod) !== 'undefined' && _v_dictSod['sp.js'] != null && _v_dictSod['sp.js'].state === Sods.loaded;

        if (sodLoaded) {
            handler();
        } else {
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { });
            SP.SOD.executeOrDelayUntilScriptLoaded(handler, 'sp.js');
        }
    };

    var initMDS = function () {
        for (var i = 0; i < initMDSHandlers.length; i++) {
            initMDSHandlers[i]();
        }
    };

    var init = function () {
        // Register MDS handler
        if ('undefined' != typeof g_MinimalDownload && g_MinimalDownload && (window.location.pathname.toLowerCase()).endsWith('/_layouts/15/start.aspx') && 'undefined' != typeof asyncDeltaManager) {
            asyncDeltaManager.add_endRequest(initMDS);
        } else {
            for (var i = 0; i < initHandlers.length; i++) {
                initHandlers[i]();
            }
        }
    };

    var registerInit = function (handler) {
        initHandlers.push(handler);
    };

    var registerInitMDS = function (handler) {
        initMDSHandlers.push(handler);
    };

    var domReady = (function (handler) {
        var fns = [];
        var listener;
        var loaded = (document.documentElement.doScroll ? /^loaded|^c/ : /^loaded|^i|^c/).test(document.readyState);

        if (!loaded) {
            document.addEventListener('DOMContentLoaded', listener = function () {
                document.removeEventListener('DOMContentLoaded', listener);
                loaded = 1;
                while (listener = fns.shift()) listener();
            });
        }

        return function (fn) {
            loaded ? setTimeout(fn, 0) : fns.push(fn);
        };
    })();


    var attachToLoad = function (functionToAttach) {
        registerInit(functionToAttach);
        registerInitMDS(functionToAttach);
       domReady(function () {
           init();
        });
    };

    _.AttachToLoad = attachToLoad;

    // THIS WILL PROTECT YOUR GLOBAL VAR FROM THE GARBAGE COLLECTOR
    window.LifeCycleHelper = _;
    if (window.Function != 'undefined' && typeof (Function.registerNamespace) == 'function') {
        Function.registerNamespace('LifeCycleHelper');
    }
})({});

var theCodeYouWantToRun = function () {
    alert('theCodeYouWantToRun');
};

window.LifeCycleHelper.AttachToLoad(theCodeYouWantToRun); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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