passing JSTL to a Javascript function using a third javascript file - javascript

I have a JSP page and I need to use my JSTL parameter in my javascript function.
I know how to pass JSTL to javascript but I want to do it by using the third .js file because my String parameter is a big string and It's so weired to show it hardcoded in JSP page
Suppose ${data} is my data and I want to use it in javascript function which is inside my main JSP file, like this:
function x(){
....
doSomeTask(myData);
}
which I want this myData come from another javascript somewhere which does have body like this:
var myData = ${data}; //this is a different js file, lets say for example alldata.js
however this solution won't work as I tested it out !
how can I keep my data separate & call it from my jsp when I'm passing ${data} to that js variable ?

You can create object like messageMap in jsp. And create key in this object assign value ${data}.
In your jsp:
messageMap = messageMap || {}
messageMap.Key = ${data}
In your javascript file can get the element and append it content to that element:
$('.element').html(messageMap.Key)

Related

How to call variable in jquery to put inside {{ Storage::url() }}

i have datatables in laravel 8 and i was encode a table to get some atribute, the code like this
Controller
i want to call r.file to get value for access the path of file,
the path file like this = "assets/file/Dr3cxy0QM2GDH1IpaWeiMZDUXfTVhl6QkazEyKYh.pdf"
Blade View
but the result like this
Browser
how to make the href value like this?
Test.pdf
You can use the jQuery .data() method to store the data in an HTML element and then access the data using the .data() method in the jQuery selector.
For example, if you have an HTML element with a class of storage-url and you want to store a variable called "url" in it, you could do the following:
<div class="storage-url" data-url="{{storage::url(url)}}"></div>
Then, in your jQuery code, you can access the data using the .data() method:
var url = $('.storage-url').data('url');

using and storing json text in JavaScript

I'm making a 2D, top-down Zelda-style web single player rpg...
I'd like to store dialog in JSON format...
Currently I'm getting the json as an external javascript file. The json is stored as such in js/json.js:
function getJson() {
var json = {
"people" :
[
{//NPC 1 - rescue dog
etc...
Then I use it in my main game javascript file as such <script src="js/json.js"></script>..`
var json = getJson();
Then use it as such:
Labels[index].text = json.people[index].dialogs.start.texts[0];
Does it matter if I keep the json as a js file in a javascript function? Or should it be stored as a .txt file then parsed?
Thanks!
It does not matter but JSON data is also JavaScript so store it as .js and later on you can add more data related functions to it if needed, btw your data file already has a getJSON function so it doesn't make sense to store it as .txt
On the other hand if an API is serving this data it need not have any extension at all.
It's better off storing the data in pure JSON format and retrieving it via jQuery.getJSON() or an XMLHttpRequest, if you're using vanilla JavaScript. Otherwise, it looks like you're adding getJson() to the global scope, which may result in a conflict if you have another getJson() defined elsewhere.
So you could have a dialog.json that looks almost the same as what you have now, just without the unnecessary getJson() function:
{
"people" :
[
{//NPC 1 - rescue dog
...
}
]
}
If you choose to use jQuery:
var dialog;
$.getJSON('json/dialog.json', function(data) {
dialog = data;
// Asynchronous success callback.
// Now dialog contains the parsed contents of dialog.json.
startGame();
});
Keeps your data separate from your logic.

Transferring javascript from a view to a seperate JS file

I am working on a legacy application and I want to move some JS code onto a separate JS file.
I will have to refractor some of the code to do this. I can put #Url.Content statements into data attributes in the HTML.
But how would I replace this line of code?
var array = #Html.Raw(Json.Encode(ViewBag.JobList));
A separate JS file will not know what #Html.Raw means.
Server side code like that cannot run in a seperate javascript file. My solution for such problems is having a short javascript part in the head that runs on the onload event. There you can set variables that you can use in a seperate javascript file:
in the head:
array = #Html.Raw(Json.Encode(ViewBag.JobList));
in the seperate javascript file:
var array;
Then, in the seperate javascript file you can do with your array whatever is necessary.
The ViewBag.JobList data is only known at HTML page generation time. To include it in an external JavaScript file, you have to have another ASP.NET resource that recalculated ViewBag.JobList and then served as part of a dynamic JavaScript file. This is pretty inefficient.
Instead, do what you're doing with the URLs: pass the data through the DOM. If you're writing into normal DOM instead of a script block, you don't need the raw-output any more (*), normal HTML escaping is fine:
<script
id="do_stuff_script" src="do_stuff.js"
data-array="#Json.Encode(ViewBag.JobList)"
></script>
...
var array = $('#do_stuff_script').data('array');
// jQuery hack - equivalent to JSON.parse($('#do_stuff_script').attr('data-array'));
(Actually, the raw-output might have been a security bug, depending on what JSON encoder you're using and whether it chooses to escape </script to \u003C/script. Writing to HTML, with well-understood HTML-encoding requirements, is a good idea as it avoids problems like this too.)
I think you need to create action with JavaScriptResult
public ActionResult Test()
{
string script = "var textboxvalue=$('#name').val();";
return JavaScript(script);
}
But, before proceeding please go through following links
Beware of ASP.NET MVC JavaScriptResult
Working example for JavaScriptResult in asp.net mvc
I would also follow MelanciaUK's suggestion :
In your javascript file, put your code inside a function :
function MyViewRefactored( array ){
... your code ...
}
In your view, leave a minimal javascript bloc :
<script>
var array = #Html.Raw(Json.Encode(ViewBag.JobList));
MyViewRefactored( array );
</script>

calling an Action using javascript

Fairly new to the PLAY Framework and because of restriction at my work we are using the 1.2.5 version, and while up til now was able to do all my process using the regular process from HTML to Controller via form submit. I would like to call an Application.Action from a JavaScript function.
While I have a form where information is inputted, another non-submit button could be clicked to go on a separate page for extra information. I want to call a JavaScript function via the "onClick" and inside the JavaScript function call the "#Application.Action(some param...)".
I need to get what is in a particular input field before calling the action.
I tried to do that with a PLAY "popup" but that does not seems to work as I can't pass the parameters along.
so here is the snippet I have:
in HTML file (extends the main.html who has all the javascript file "include")
<form>....
some input fields here
submit button here
</form>
<button onclick="myFunction()" data-role="button" style="width: 5em">Click here</button>
in the JavaScript file that is included in main.html I have something like this
function myFunction() {
var inputField1 = document.getElementById('inputField1').value;
var inputField2 = document.getElementById('inputField2').value;
var inputField3 = document.getElementById('inputField3').value;
window.location = "#{Application.moreInfo(inputField1, inputField2, inputField3)}";
}
Of course that does not work
Is there a way to do it like that?
Do I have to create a route for that?
I was able to reach a separate page by replacing
window.location = "#{Application.moreInfo(inputField1, inputField2, inputField3)}";
with
window.location.href='/goThere';
as long as I have a route
/goThere Application.goThere
but I could not figure out a way to pass parameters, I tried to set the route like
/goThere/{inputField1}{inputField2}{inputField3} Application.goThere(inputField1...)
but I guess I do not have the right syntax either.
Is there a way to call an Application.Action and pass it parameters/fields from a JavaScript function.
Any help is appreciated
The built-in #{jsAction /} template tag does exactly what you want.
Example:
Assume you have a route
GET /moreinfo/{foo}/{bar} Application.moreInfo
You can use the result of jsAction to get the correct URL with the parameters you want:
var fieldOne = "I'm a Javascript variable";
var fieldTwo = "Really? Me too";
var moreInfoAction = #{jsAction #Application.moreInfo(":foo", ":bar") /};
// and since it looks like you want to set the current location
// to your freshly obtained URL:
window.location.href = moreInfoAction({"foo": fieldOne, "bar": fieldTwo});

JSTL in javascript (get list of jbean)

I'm developing a shortned url project . And I would use a javascript function to display a pie diagram .
I want to know if it's possible to pass a list of Javabean (jst , jsp ) to a javascript function ( array , table..) ?
One efficient way to achieve this is to create a JSON structure on server side and pass it on to the client side. I suppose your chart data will be in an array or tabular format.
There are various JSON libraries available like Jackson. Refer to Jackson example.
Once you have constructed appropriate JSON object on Server side, you can refer to it on JSP by assigning the value in one line call.
<script type="text/javascript">
var jsonObj = '<c:out value="${jsonObject}"/>';
// you can refer to jsonObj in rest of the script
// including external JavaScript file
</script>
In above example jsonObject is constructed on server side in Servlet or controller etc.

Categories

Resources