1
_spBodyOnLoadFunctionNames.push("FetchURL");
                function FetchURL()
                {
                    // Custom JavaScript methods
                   var ctx = new SP.ClientContext();
        var site = ctx.get_site();
        ctx.load(site);
        ctx.executeQueryAsync(function(s, a){ currURL=SP.Utilities.Utility.getLayoutsPageUrl("");
                                            });
                    }

The above method returns the URL, however, sometimes it returns undefined, which causes errors. How to tackle this?

Code is placed in head of the masterpage... in scripts tag.

variable
  • 4,473
  • 13
  • 75
  • 139
  • do you need to call get_site for anything? otherwise there is no need to load it with ctx.load; you can call the SP.Utilities.Utility.getLayoutsPageUrl synchronously, without calling executeQueryAsync – MdMazzotti Apr 04 '14 at 10:18
  • What returns undefined? The function FeetchURL has no return and will then always return underfined. The global variable currURL will be set asynchronously, as ctx.executeQueryAsync is asynchronous, which means in you code you can't know when it is set – eirikb Apr 04 '14 at 10:18
  • @MdMazzotti alert(SP.Utilities.Utility.getLayoutsPageUrl()); doesnot work. can you give me a solution, eirikb. – variable Apr 04 '14 at 10:21
  • @variable it's a function, you must call it like SP.Utilities.Utility.getLayoutsPageUrl() – MdMazzotti Apr 04 '14 at 10:23
  • If i put the SP.Utilities.Utility.getLayoutsPageUrl in the spBodyOnLoadFunctionNames() then it works, why is this happening? Im confused – variable Apr 04 '14 at 10:23
  • @variable because it's defined inside the sp.js file. You need to make sure the file has been loaded before calling it – MdMazzotti Apr 04 '14 at 10:24
  • MdMazzoti, I got around 100lines of js code, is it good practice to put all of it in execute or delay untill sp.js is loaded? – variable Apr 04 '14 at 10:29
  • try using _spPageContextInfo.layoutsUrl instead. http://blah.winsmarts.com/2013-2-_sppagecontextinfo_is_your_new_best_friend.aspx – Derek Gusoff Apr 04 '14 at 10:47

1 Answers1

3

The SP.Utilities.Utility.getLayoutsPageUrl is contained within the sp.js file. You have to make sure that sp.js has been loaded, before calling the function.

SP.SOD.executeFunc('sp.js', 'SP.Utilities.Utility.getLayoutsPageUrl', getCurrentUrl);

function getCurrentUrl(){
  currentURL = SP.Utilities.Utility.getLayoutsPageUrl(""); 
}
MdMazzotti
  • 4,787
  • 3
  • 17
  • 35
  • thanks for this. it works, however I am using it in a big js code, have posted the issue here http://sharepoint.stackexchange.com/questions/95260/executeordelayuntillscriptloadedcodetorun-sp-js-for-entire-script-function – variable Apr 04 '14 at 10:44