Set an url globally in JavaScript - javascript

In an ASP.NET MVC application, we call web service and web API methods from JavaScript files. Whenever the url gets changed, we have to modify the url in many .js files.
As we access the url in JavaScript, is there anyway to set it globally like web.config in .NET?
Thanks.

You can just have this or something similar in your view:
<script>
window.apiUrl = '<%=ConfigurationManager.AppSettings["apiUrl"]%>';
</script>
(or if it's Razor?...)
<script>
window.apiUrl = '#(ConfigurationManager.AppSettings["apiUrl"])';
</script>
That way, your other scripts can simply reference:
var url = window.apiUrl;

You can declare a global variable in the view(call VewBag in the Controller),and This variable in the configuration

Related

Send arguments to use function in JS Use API | AEM 6.5

I am trying to get the url in my Javascript file. But seems like window.location work in JS Use API neither. So I was trying to send the URL as an argument but that's failing with an error.
My JS code:
"use strict";
use(function () {
var url = this.url;
/other code/
});
My HTML code:
<sly data-sly-use.item="'myfile.js' # url=value">
HTL/Sightly is a server-side template language. The scripts (including JS Use Objects) are compiled and ran once, when the page is rendered. To get the current URL/location you can leverage SlingHttpServletRequest#getRequestPathInfo. The current request is available as request as part of the HTL Global Objects.
Also, regarding getting errors when using <sly data-sly-use.item="'myfile.js' # url=value">, that's most probably because value is not defined as a variable name in the HTL server-side rendering context. Using <sly data-sly-use.item="'myfile.js' # url='https://www.test.com/'"> should work.

How do I get jQuery ajax url prefixes to resolve controller action methods?

I'm sure this question has been asked multiple times, but the one example of the problem I'm having was asked about here.
Basically, if I have an ajax call to /Controller/Action, it works fine if I'm using my local development server of localhost/Controller/Action.
If I publish to UAT, the url needs more information. It's now server/application/Controller/action, which obviously breaks my ajax call.
<%: Url.Action("MyAction") %> solves this, but doesn't exist in the context of a seperate javascript file.
Currently, I have a javascript variable 'urlPrefix' in my app.js file, which I have to change between ""and "applicationName" everytime I debug locally or release to a different server.
What's the easiest way of solving this?
You can use:
#Url.Content("~")
to resolve the root path of the application, so there'll be no need to change it between deployments.
One way to implement this is to add the following to your <head> in _layouts:
<script type="text/javascript">
var rootPath = '#Url.Content("~")'; // includes trailing /
</script>
(use your namespace as required)
then you can generate your actions such as:
var url = rootPath + 'controller/action/' + id

How to load a REST call through a script tag

I understand that this a bit odd of a question but here I go. I am writing an application that will be switching environments (dev, test, prod, etc). I need the base URL for my REST calls to change as I switch environments. Well, our current solution (and I am all ears for better solutions) is a local REST call asking the server what environment I am in and what URL I should be using for my base. The external REST calls are separated from the front end completely.
With the local REST call I could do an ajax call to get the data somewhere in my javascript or I could include the REST call as follows:
<script src="/rest/configs"></script>
The problem with the above solution is that it returns an object that is not assigned to a variable thus throwing errors. So my over all question is, Can you load a REST call through a script tag straight into a variable and if so, how?
If you do this with a script tag the response of the request ( not AJAX at all ) will be parsed and executed as javascript.
What you could do is to return valid Javascript, rather than JSON object. Something like
window.config = {"env":"test"};
rather than
{"env":"test"}
Other option is not to do this with script tag and just write inline javascript with an ajax call. If you use jQuery it would look like :
<script>$.get("/rest/configs", function(config) { window.config = config; });</script>
This will do the Ajax call and assign it to a global variable config. Of course you should make some adjustments and execute the rest of your javascript after this is executed.
Anyway as a standard, this value is usually hard-coded in the scripts. I would suggest to create a script that is modified for test/dev/production environments.
Can't your rest call just return a Javascript object, like so:
var env = "experimental";
Your webpage should be able to interpret this as Javascript and the env variable should be usable in the rest of your page:
<html>
<head>
<script type="text/javascript" src="/rest/configs"></script>
<script type="text/javascript">
console.log("env: " + env); // prints env: experimental
</script>
</head>
<body></body>
</html>

Getting the contextPath into external JavaScript

How to access ${pageContext.request.contextPath} of jsp into a external javascript file ?
before the script in which you'll need it, you should be able to include something like this. then access it by variable name.
<script>var myContextPath = "${pageContext.request.contextPath}"</script>
<script src='theScriptINeedContextFor.js'></script>

Using JavaScript Variables On Different Files

I have a js variable defined in a js file like so :
onlineUsers.js :
var _onlineUsers=new Array();
I'm then linking the js file into index.html like so
<script type="text/javascript" src="onlineUsersVars.js"></script>
and I know for sure it gets a value after awhile since I've checked it with alert .
However , when I try to do the same with another html file , e.g file2.html
then link the js file to get the same variable
file2.html :
<script type="text/javascript" src="onlineUsersVars.js"></script>
and check the value , the value is nothing .
Anyone has a clue what I'm missing ? Do javascript variables 'die' after being linked to one page ? How can I share the same global javascript variable between many html pages ?
You will have to include the script (onlineUsers.js) on every HTML page. And the variable (_onlineUsers) will need to be re-instantiated on every HTML page.
Yeah if you go from file1.html to file2.html, even though you have the same JS file on both files, the values will all clear. The best way to pass variables from page to page would be by using cookies.
Try using HTML5 localStorage to store the variable and then call it each time you need to.
function onlineUsers() {
var _onlineUsers=new Array();
localStorage.onlineUsers = _onlineUsers;
}
Then this value will be available anytime you need it. Although that is client side not server side.

Categories

Resources