How do I use javascript variable in LuCI Lua markup? - javascript

I am creating an HTML file for use with OpenWrt LuCI web interface. As discussed here: http://luci.subsignal.org/trac/wiki/Documentation/Templates I am using the Lua Markup language to run a Lua function called runDiag and I need to pass the javascript variable option to the runDiag function. I can't figure out how to make this work. I have tried various modifications to the markup inside the displayDiag function without success.
Can anyone help?
Example:
<%-
function runDiag(option)
return option
end
-%>
<script>
function displayDiag() {
var option = document.getElementById('iface').value;
document.getElementById('diag_text').innerHTML = '<%- write (runDiag(option)) -%>';
}
</script>

You can't do this. The Lua template is ran on the server, and the JavaScript code is ran on the client (i.e. web browser). They can't communicate.
The Lua code simply generates an HTML file to send to the client. It doesn't know about JavaScript; it's just some text that it's giving to the client. Here, option refers to a nonexistant Lua variable, which has the value of nil.
Conversely, the JavaScript code has no knowledge of the server-side Lua code. It just gets whatever the server generated. Thus, it only sees this line:
document.getElementById('diag_text').innerHTML = 'nil';
To communicate with the web server, you will need use AJAX or some other protocol.

Related

Run Java method in Javascript in Freemarker template

I would like to run method over my Java object in Freemaker template but in Javascript. Could be also directly in Freemarker but I need to run it on click.
I have issue that following method doesnt run:
actual_id.setActual_id(variable) ;
And I have following Java code:
Setting actual_id= new Setting("-");
Map<String, Object> data = new HashMap<>();
data.put("items", items);
data.put("actual_id", actual_id);
public Setting(String actual_id) {
this.actual_id = actual_id;
}
public String getActual_id() {
return actual_id;
}
public void setActual_id(String actual_id) {
this.actual_id = actual_id;
}
This is my Freemaker template:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>function myFunction(variable) {
alert(variable);
actual_id.setActual_id(variable) ;
location.reload();}
</script>
<#list items as item>
<p>${item.name}: ${item.id} <button type="button" id="${item.id}" onclick=myFunction("${item.id}") >Details</button>
</#list>
EDIT1:
I am also trying something like this:
onclick="${actual_id.setActual_id(item.id)}"
but cannot trigger activity from onclick.
EDIT2:
I already almost found solution. Following code executes Java method, I just need to figure out how to quote "variable" to load javasript value into it.
function myFunction(variable) {
alert(variable);
var idd ="${actual_id.setActual_id(variable)}";//here variable value needed
alert(idd);
location.reload();
}
Here is a quote from the Apache FreeMarker Project front-page:
(https://freemarker.apache.org/)
What is Apache FreeMarkerâ„¢?
Apache FreeMarkerâ„¢ is a template engine: a Java library to generate
text output (HTML web pages, e-mails, configuration files, source
code, etc.) based on templates and changing data. Templates are
written in the FreeMarker Template Language (FTL), which is a simple,
specialized language (not a full-blown programming language like PHP).
Usually, a general-purpose programming language (like Java) is used to
prepare the data (issue database queries, do business calculations).
Then, Apache FreeMarker displays that prepared data using templates.
In the template you are focusing on how to present the data, and
outside the template you are focusing on what data to present.
Figure [Photo/Image Not Posted]
This approach is often referred to as the MVC (Model View Controller)
pattern, and is particularly popular for dynamic web pages. It helps
in separating web page designers (HTML authors) from developers (Java
programmers usually). Designers won't face complicated logic in
templates, and can change the appearance of a page without programmers
having to change or recompile code.
While FreeMarker was originally created for generating HTML pages in
MVC web application frameworks, ** it isn't bound to servlets or HTML
or anything web-related.** It's used in non-web application
environments as well.
https://freemarker.apache.org/
I, myself, program Java & JavaScript web-servers on Google Cloud Server all day long. The only way to make a JavaScript function talk to a Java Function is through an HTTP GET / POST call to a Java-Servlet or, also, an old-school JSP Page. Though it says (explicity) right on the top-level domain page of the website that "Freemarker is not bound to Servlets" - that actually means the software classes / package does not have to run inside of a web-environment at all - perhaps on your desktop computer without a web-browser.
What I do know with an extremely high degree of certainty is that communication between the client (on a web-browser) and a server (a web-server) is always done through HTTP GET / POST requests. JSON, AJAX are common for higher communicating large amounts of data. If you expect a JavaScript method to make a call to a Java Class on the back-end, you will need to include a Servlet or JSP class - and the whole 9 yards to boot.
NOTE: I have not used Apache FreeMarker, but I program Java/JavaScript all day long. Judge accordingly! According to the Apache web-site, FreeMarker is of assistance in "programatically or automatically generating the HTML for pages" (which is what C# is good at) - which is actually something I do for my web-site, often, but (alas!) I don't use Apache's product. What that means is FreeMarker can help the generating of HTML more efficiently using Java Classes on the back-end server side ...
But the rules of how Java and Java-Script communicate have not
changed...
Long story short - you must include JavaScript calls such as:
calling a java servlet from javascript
How to send request from javascript to servlet?
How to call servlet from javascript

Accessing a javascript element in server side JSP

I have a script tag in a JSP and in that, I am reading a server side variable which I have read from the session.
I need to use a javascript variable (campaignIndex) in that server side variable ( getCreditAmountMax) like so:
<script>
var campaignIndex = jq111("select#campaigns").find(':selected').index();
GT.utilities.updateData(creditAmountDiv, "maxAmount", '<%=creditCampaignsModel.getCreditCampaigns().get(campaignIndex).getCreditAmountMax()%>', false);
</script>
Can I do that?
It is possible to dynamically generate Javascript code in JSP. It is not possible that JSP-expressions get reevaluated at client. From the point of view of the Javascript code it's only a constant.
Similar question: Access to Java model List from Javascript/JQuery dynamically.

Define a string java with a js variable [duplicate]

Ello there,
I'm trying to assign the value of a javascript variable to a java variable. But I don't have clue how to do this? Say for example I have this:
<html>
<head>
<script type="text/javascript">
function return variable(){
var a = "hello";
return a;
}
</script>
</head>
<body>
<%
//The java code
String b = //how do I get that javascript variable here?
%>
</body>
</html>
Java script plays on browser where java code is server side thing so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server
HTML
<input type="hidden" id="hiddenField"/>
make sure this fields lays under <form>
Javascript
document.getElementById("hiddenField").value=yourCalculatedVariable;
on server you would get this as a part of request
You need to read something about a JSP's lifecycle. Try this: http://en.wikipedia.org/wiki/File:JSPLife.png
JavaScript runs on the client, but in order to change the jsp, you need access to the server. This can be done through Ajax(http://en.wikipedia.org/wiki/Ajax_%28programming%29).
Here are some Ajax-related links: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
The answer is You can't. Java (in your case JSP) is a server-side scripting language, which means that it is compiled and executed before all javascript code. You can assign javascript variables to JSP variables but not the other way around. If possible, you can have the variable appear in a QueryString or pass it via a form (through a hidden field), post it and extract the variable through JSP that way. But this would require resubmitting the page.
Hope this helps.
JavaScript is fired on client side and JSP is on server-side. So I can say that it is impossible.
I think there's no way to do that, unless you pass the value of the JavaScript var on the URL, but it's a ugly workaround.
you cant do it.. because jsp is compiled and converted into html server side whereas javascript is executed on client side.
you may set the value to a hidden html element and send to servlet in request just in case you want to use for further
As JavaScript is client side and JSP is Server side.
So Javascript does not execute until it gets to the browser,
But Java executes on the server.
So, Java does not know the value of the JavaScript variable.
However you assign value of Java variable to JavaScript variable.

Passing Value from C++ to Javascript

i have a c++ file which reads values from a sensor and I want to display those values on a website dynamically. So Im looking for a way to pass these values(integers) from my cpp file to an javascript which displays them on the site.
My first, simple try was to write the values into a js file as variables every second from my cpp script. The Js then uses this file as a source and displays its variables on the site:
cpp:
fprintf(file, "var mx=%d, my=%d, mz=%d, ax=%d, ay=%d, az=%d, gx=%d, gy=%d, gz=%d;\n",
imu.raw_m[0], imu.raw_m[1], imu.raw_m[2], // M = Magnetometer
imu.raw_a[0], imu.raw_a[1], imu.raw_a[2], // A = Accelerometer
imu.raw_g[0], imu.raw_g[1], imu.raw_g[2] // G = Gyroscope
);
html/js:
<script src="./imu.js" type="text/javascript"></script>
The Problem now is of course, that I need to refresh the page all the time, because the imu.js file is cached by the website.
I'd rather have a way to directly pass to integers from the cpp file to the js script. I read something about json or Googles V8 script. But I'd like to hear your suggestions first.
By the way, Im running this on a raspi, if this is important.
Thanks for your help
EDIT:
I'm goning to try it with a mysql database, in which my cpp file writes the data from the sensor with Connector/c++ from http://dev.mysql.com/doc/connector-cpp/en/ and my website reads them.
You could compile your C++ code into a Node.js plugin, you can then register a JavaScript function with your plugin which the C++ calls when it updates the value. That way you can pass values directly from C++ into Javascript in a managed and controlled way.
Node.js has the added benefit of being able to host your webpage and do all the Websocket and HTTP stuff that can be a pain in C++.
You do not have to refresh if your script is smart about how to access the data file! In case you do have a webserver at hand: Take care that your data file is accessible by your webserver and then let your script request the file via ajax (link to w3schools)
I'm doing something similar on a BeagleBone Black. With websocketd you can turn pretty much any program into a websocket endpoint and then send data via stdin and stdout commands. This would be a particularly good solution for you since websockets are designed to handle information that's constantly changing.

Passing JavaScript variable to smarty

I'm having some trouble passing a variable from JavaScript to smarty.
Example:
{literal}
<script type="text/javascript">
var js_variable = 110;
</script>
{/literal}
jQuery('div.fakbox_msg').html("{/literal}{lang_sprintf id=100013 1=js_variable}{literal}");
You cannot do that in an easy way. PHP, and by extension Smarty, is parsed and run on the server side before the browser get the data. JavaScript is run on the client side when the browser parses the HTML, CSS and Javascript that the server sent.
You will have to make a new HTTP request in some way, sending the new data. You can do that by reloading the entire web page and sending stuff in the querystring (after ? in the URL), or slightly more advanced by doing an Ajax call from your JS code and make JS do the changes of the page that you desire. The latter is more complex and requires some knowledge of Javascript, but the page does not need to be reloaded in its entirety.
for more info :
Assign JavaScript variable to Smarty variable
I never used Smarty, so I may be wrong, but from what I see on your code. this should work:
jQuery('div.fakbox_msg').html("{/literal}{lang_sprintf id=100013 1=" + js_variable + "}{literal}");
Smarty cannot use client side variables, such as the ones created by JavaScript.

Categories

Resources