Is there a simply way to read bean values in a .js file?
I have an external JS file, arrays.js, which contains some arrays, used to populate a series of within a JSP page.
Now I need to fill the content of those arrays reading values.
I have to use the external js file, because it also contains lots of other methods to make the application work.
Thank you in advance
Simplest way is to let JSP print it as a global JS variable so that it's visible to the scripts which execute after DOM ready. E.g.
<script>var bean = ${beanAsJson};</script>
where ${beanAsJson} prints the bean in JSON format. You could use among others Gson for this.
Another way is to let the JS code send an ajax request to a servlet which writes exactly that bean in JSON format to the response. E.g. with little help of jQuery:
$.getJSON('jsonServlet', function(bean) {
// ...
});
See also:
accessing session variables in javascript inside jsp
How to use Servlets and Ajax?
Populating cascading dropdown lists in JSP/Servlet
In arrays.js file create a function function populateArray(arg1, arg2). Now you have a global function accessible from anywhere on your page, pass the values that you want to populate the arrays with as arguments to populateArray function and inside the function write the logic to populate your arrays.
Related
I have created two jsp pages. I passed a list from jsp page and displayed the contents of the list in the second page using this: ${user.rate},${user.location}etc..
Now, I want to store one of these elements in a local variable for performing some arithmetic operations. I don't know how to save the variables locally and use it.
Kindly help me.
I found the answer. I used c tags to store my values.
<c: set var=name_of_variable value=${user.location} />
And I can access the variable using the 'name_of_variable'.
I am doing some development in moodle 3.7 for a new admin tool plugin. In this plugin I am generating a page from a custom made .mustache template. This template contains a number of values that are defined and managed within it, that I want to access within my .php file once a submit button is pressed.
Currently however I am unable to access these submitted values that are defined within the template. I can see their values in debugging under $form->_form->_submitValues but I cannot get to them due to _form being a protected variable of $form. I called $form->get_data(), but that only gave me access to the elements that I defined in php as non html elements (hidden for example), not in the template. I'm not sure if this is the right place to ask this question, but if anyone has any help they could give me on a path forward it would be much appreciated.
I am adding the template to the page using the function:
$mform->addElement(
'html',
$OUTPUT->render_from_template(PLUGIN_TOOL_NAME/members', $rendercontext)
);
Please let me know any other information you may need.
Any variables that you want to have access to must be defined in the mform using these functions:
$mform->addElement('hidden', 'VARIABLE_NAME');
$mform->setType('VARIABLE_NAME', PARAM_INT);
Any JavaScript that needs to update these values must be in a separate .js file, not in your template. If the JavaScript works in your mustache file, it will still do exactly the same thing if you put it in a different .js file, as long as that .js file is included on the page.
One thing to note: if you use the functions I defined above, the variable will not have an ID. instead it will have a name equal to whatever you put as VARIABLE_NAME. This means however that you cannot use document.getElementByID() to get the instance of your variable. instead you will have to use document.getElementsByName("VARIABLE_NAME")[0] to get access to your element.
If both of these things are done than you should see the value update and be sent to your mform on submit within the $data variable.
I'm initializing a JSP string inside a Liferay portlet:
String json = "{}";
// returns json
json = LiferayPortlet.makeCurlCall();
...
<script>
$(window).load(function(){
//initialize js variable
jsData = "${json}";
// initialize the page
initializePage(jsData);
});
</script>
The issue I'm having is that LiferayPortlet.makeCurlCall(); is returning json, but jsData is not being initialized to it, instead its being set to "". Is there a way to initialize jsData to the json that is being returned from the function above?
Don't do it
You cannot initialize a JavaScript variable with a scriptlet or JSTL. The Java code is executed on the server and will not execute in top down order on your jsp page.
While I don't recommend this you can use the following
<script type="text/javascript">
var message = '<c:out value="${json}"/>';
</script>
That will technically work - however I want to stress that I do not recommend this. Maybe you can explain exactly what you are trying to accomplish and we can recommend a more optimal way of doing it.
JSTL v. Scriplets
You might also have a scope issue using JSTL and scriplets together indiscriminately. They are of different scopes. JSTL works with the following scopes.
page
request
session
application
Scriplets are in the page scope always. So while your code doesn't contain this issue it most likely will be something you will encounter.
Recommendation
If you are using Liferay, I suggest you learn Alloy UI (a JavaScript library) and become comfortable with their AJAX modules. Generally, when I see the code you posted, it is better to have an AJAX function that makes a GET call to your portlet for the JSON when it is needed.
In my javascript files, I have too much hardcorded url that references controllers actions. Sometime, I also have messages displayed directly from my javascript.
What is the best way to remove all these hardcoded strings from javascript files?
Step one, use T4MVC to automatically generate a structured set
of .NET classes that describe your ASP.NET MVC's application
structure
Step two, create a new partial view that defines server-side
information described by T4MVC as a set of Javascript constants.
<script type="text/javascript">
var SHOPPING_CART_DETAIL_URL = '#Url.Action(MVC.ShoppingCart.Detail(Model.ShoppingCartId))';
var CLIENT_DETAIL_URL = '#Url.Action(MVC.Client.Detail(Model.ClientId))';
var USER_IS_ADMIN = #(User.IsInRole(Roles.Admin) ? "true" : "false");
</script>
Step three, include this partial view in the head of whatever page
you need it. You could also include it in the head of your general
page layout. Make sure this loads before the rest of your JavaScript files.
Step four, use your newly defined JavaScript constants throughout your JavaScript files.
For that purpose I use T4MVC. It will allow you to use strongly typed objects in place of literal strings. You will need to initialize your javascript in your views, but other than that it works great.
For messages etc. here are some ideas: what are the different approaches to multilingual javascript applications
If you want to avoid using T4MVC, you could make a Controller that parses JS files. Just configure a route in Global.asax that catches all the javascript urls, and that action will ready the JS file, parse it, return a result with the URLs.
routes.MapRoute(
"Javascript",
"{url}.js",
new { controller = "Javascript", action = "Parse" }
);
Then write an action that reads the requested URL, finds the JS file, replaces values based on a Key/Value dictionnary. Perhaps even externalize that Key/Value dictionnary if could need that. The rest is up to you.
Another option would be to use a controller action that returns Javascript code. That javascript code would be a list of variables filled with URLs that are MVC generated.
...not more to add apart the title:
I have a list functions which formats the result of a view according to some values contained in an array
var array=[val1, val2, val3...]
As this array is also used in my javascript client-side functions, and grabbed from a globvar.js file on the server, is it possible to include it in a list functions?
How?
Should I execute an ajax request?
thanks for answering.
You can put it in a CommonJS module: http://wiki.apache.org/couchdb/CommonJS_Modules
You can't do ajax requests within CouchDB.
EDIT: latest documentation is at http://docs.couchdb.org/en/latest/query-server/javascript.html#require