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

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.

Related

Set an url globally in 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

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>

How to pass parameters to a javascript ajax POST so that Rails will interpret them?

In a Rails 3.2 app I have a coffeescript function that includes a POST to create an Asset with attached file (using Carrierwave)
link = url_to_file
parent = $('#dom_obj').data('id')
$.post( url, { remote_file_url: link, parent_id: parent } )
This gives the following log:
Started POST "/assets" for 127.0.0.1 at 2013-10-05 14:53:57 +0700
Processing by AssetsController#create as JS
Parameters: {"remote_file_url"=>"https://the/correct/path", "parent_id"=>"520"}
In the controller
#asset = Asset.new(params[:asset])
#asset.save
I have some other methods to create an Asset, they all work fine. The variables passed into this ajax call are also correct. But #asset.save is failing due to an error in the uploader which implies that the parent_id is not being set correctly.
As all the components of this work perfectly via other upload pathways, my only conclusion is that the jquery ajax call is incorrect, and I guess I'm not setting the parameters correctly (would params[:asset] in my controller correctly interpret the parameters logged above?).
How to pass parameters to a javascript post so that Rails will interpret them correctly? Any guidance much appreciated as I'm going round in circles!
from the log you provided, there is no such thing called params[:asset] provided by your POST call. So, what would work is to do that in your controller
#asset = Asset.new(params)
#asset.save
or if this doesn't work you could try
#asset = Asset.new(:remote_file_url => params[:remote_file_url], :parent_id => params[:parent_id])
#asset.save
or another solution would be to not change your controller but change your form input names in your html to asset[remote_file_url] and asset[parent_id]

Zend passing server url / parameter to javascript file

For my application I need to pass a parameter through zend to my exter javascript file.
I need the server url in the javascript with the language parameter.
my javascript is placed in /js/javascript.js
I've tried the follow
layout.phtml
$this->headScript()
->prependScript('BASE_URL = "test";')
->appendFile('/js/javascript.js');
javascript.js
var url = BASE_URL
But my firebug console keeps saying that BASE_URL is not defined. What
is the good way to do this?
Regards.
Nicky
First you include javascript.js, and just after it you prepend script before appended javascript.js.
$this->headScript()
->appendFile('/js/javascript.js')
->prependScript('BASE_URL = "test";');

Categories

Resources