Convert a javascript variable to scala in play framework - javascript

I have some variables in javascript:
var something = 1;
var url = "#CSRF(routes.Some.thing(something))";
I get an error during compilation because "something" does not refer to the javascript variable, in other words; the compiler can't identify it. Is it possible to convert/inject the javascript variable somehow? Also, does this work in real time in javascript or do I need to prepare an "#CSRF(routes.Some.thing(something))" array containing each possible "something" value?
It's supposed to be a simple rest call, seen in routes file:
/something/:something controllers.Some.thing(something : Long)
An alternative would be to use a form, but I want to try not to.

You need to use a Javascript Routing and add the CSRF token to the request.
Javascript Rounting description: https://www.playframework.com/documentation/2.6.x/ScalaJavascriptRouting
Look at my answer to the question with explanation how to use it for assets("Correct and long solution"), the usage for other activities is the same: How to update src of a img from javascript in a play framework project?
So in your case, the Javascript routes generation can look like:
JavaScriptReverseRouter("jsRoutes")(
routes.javascript.Some.thing
)
And in the JavaScript:
var something = 1;
var url = jsRoutes.controllers.Some.thing(something).url;
The last - do not forget to add Csrf-Token header to the request.

Related

Javascript create array from local words.txt 2021

I have a txt file called test.txt.
Inside of it there are words that are basically laid out like this.
ability
able
about
above
accept
according
account
across
act
action
activity
actually
add
address
administration
admit
adult
affect
after
again
against
age
agency
agent
ago
I want to use these words turn them into an array and store into one variable.
Something like this.
var words = ["ability", "about", "above", "action"...];
I am only using javascript and nothing else how do I do this?
Assuming you are using node.js since you are accessing a file.
const fs = require('fs');
let array = fs.readFile('./test.txt').split(/\r?\n/g);
Otherwise the answer is: JavaScript is executed client-side and won't handle files.
try it:
file.split(/\r\n|\r|\n/g)

How to get element from HTML stored in variable

I am running an API to retrieve email from external system. I managed to get HTML code from the returned JSON and store it in a variable. Now, I would like to run some further operations on this HTML - for example get all elements with
[data-type="whatever"].
It would be easy in html document:
var x = document.querySelectorAll('[data-type="whatever"]');
However the HTML document I want to work with is stored in the variable so the code I write in API does not recognise it as a document. How can I do it? Any suggestions with vanilla JS?
You can try something like this.
let rawDoc = '<html><head><title>Working with elements</title></head><body><div id="div1">The text above has been created dynamically.</div></body></html>'
let doc = document.createElement('html');
doc.innerHTML = rawDoc;
let div1 = doc.querySelector('#div1');
console.log(div1)
What if you use innerHTML? or maybe I don't fully understand the question.
Since you are working without a document you have 2 options.
1. Use regex to get what you need (something like /<.+>.+ data-type="whatever".+<\/.+>/gi) should do (but for an exact match you may need to make something better).
2. Insert the html in a hidden part of the dom and select what you need from it (like in Zohir answer - he provided a good example).
I used following code with angular to store whole html content in a variable and pass it as argument to call API.
var htmlBody = $('<div/>').append($('#htmlBody').clone()).html();
This might work for you as i was working on sending email to pass invoice template so try this.

How a Session variable set in Server be accessed in External javascript file? [duplicate]

I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.

In JavaScript, how do I get the URL of the JavaScript file, not the location URL?

I would like to use a query string parameter so that way I can specify the name of a DOM element.
I have some code that requires the height of the header and I would like that code to work for any theme. Only at times the header uses the <header> tag, at times it has a specific identifier, at times it is a specific class... to be able to reuse that code over and over again, I'd like to include it in a way such as:
<script src="https://www.example.com/js/my-script.js?c=header"></script>
What I want to be able to do is get the "?c=header" part from that JavaScript URL to send search a DOM object with jQuery(".header"). Do we have a way to know the URL of the JavaScript itself from the JavaScript being executed?
Obviously, I know of window.location.href and that's not the URL I'm looking for.
As mentioned by #Kaiido in a comment, there is the document.currentScript parameter that gives you access to the <script> tag which is currently running. Only there is a small trick to it, that parameter is defined on the first pass, not when executing functions within your script.
So what one can do is save that information, or at least what you need from that object, in the global scope or a static in your object.
In my case, I just did the following:
// Script to tweak things on many websites
var this_script_url = document.currentScript.src;
jQuery(document).ready(function()
{
// at this point: "document.currentScript === null"
var qs = this_script_url.split("?", 2);
if(qs && 2 == qs.length)
{
... // handle qs[1] which is the query string (a=1&b=3&...)
}
});
Please make sure you don't use a global name that's too generic. It should include the name of your script or abbreviation thereof. Otherwise you are likely to clash with another script's global.
Now if you have a prototype object, I would suggest you use a static member instead of a global.
var my_class = {};
my_class.script_url = document.currentScript.src;
// and later you can reference it directly as in:
url = my_class.script_url;
This way you are more likely to avoid clashing problems (the only thing that needs to be changing in case of a clash is the name my_class).
At this point, the ES5 or ES6 class keyword does not offer you to create variables.

Use dynamic element ID in #{rich:clientId()} function

We can get element by static ID using rich:clientId() function as follows
document.getElementById('#{rich:clientId(JSF_ID)}').click();
However, I need to use a dynamic ID which takes the form of var + "_ID" where var can be employee, student, etc and thus resulting in employee_ID, student_ID as actual ID.
I tried as follows:
dynamicID = var + '_ID';
document.getElementById('#{rich:clientId(dynamicID)}').click();
However, it didn't work. How can I achieve this?
It looks like you are setting dynamicID via JavaScript, am I right?
If yes, the EL-expression #{rich:clientId(dynamicID)} cannot be evaluated as EL on the server during the rendering of the page since the dynamicID is only available on the client (=browser) when the page has already been built up on the server and sent to the browser.
Where does var come from? How is it applied to the component with the dynamicID? Can't you use the same approach for the getElementById?
For concatenating a variable with a constant in JSF on server-side, see the following already answered post Concatenate strings in JSF/JSP EL and Javascript. Basically it gives you a how-to in creation of an own concatenation function for jsp/jsf. Works pretty need.
As a hint: you can use #{rich:element(JSF_ID)} instead of document.getElementById('#{rich:clientId(JSF_ID)}') to keep the source readeable - it will render identical results.
Good luck...

Categories

Resources