Calling Java function within Javascript in JSP application - javascript

I would like to access a variable and a set of functions from within a javascript segment. I have two files:
testJSP.jsp
<%#page import="test.tester"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%
String thing = "Exciting String";
tester testy = new tester(thing);
%>
<input type="submit" onclick="test()" value="Sample Text" />
<div id="testDiv" >Boring String</div>
<script language="javascript" >
funciton test() {
document.getElementById("testDiv").innerHTML = <%=testy.getString()%>;
}
</script>
</body>
</html>
tester.java
package test;
public class tester {
private String privy;
public tester(String testString) {
privy = testString;
}
public String getString() {
return "new " + privy;
}
}
Essentially, when the button is clicked, I want the element with id "testDiv" to be changed according to the function in the java file. I may be overlooking a very simple method, or perhaps there is a far more complex way of approaching this seemingly simple problem.

Related

How to show the output of a function that takes two arguments in brython?

I have this brython script that is supposed to take in two inputs, process them in a python function imported from another python file, and generate one output into a textarea when the inputs are typed in. I can't figure out how to do that as the bind() only allows one.
Here is how the process looks like
The following code only works with one input
<textarea id="input_one"></textarea>
<textarea id="input_two"></textarea>
<textarea id="output"></textarea>
<script type="text/python">
import project
from browser import document
def function(x):
document['output'].text = project.main(x.target.value)
document['input_one'].bind('input', function)
</script>
Assign names to the fields in the document and refer to them in the bound function.
That way you can retrieve their values and pass them along to project.main.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/brython#3.10.7/brython.min.js">
</script>
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/brython#3.10.7/brython_stdlib.js">
</script>
</head>
<body onload="brython()">
<script type="text/python">
from browser import document
import project
element_x = document['input_one']
element_y = document['input_two']
element_result = document['output']
def oninput(arg):
x, y = None, None
try:
x = int(element_x.value)
y = int(element_y.value)
except ValueError:
pass
if x and y:
element_result.value = project.main(x, y)
else:
element_result.value = ''
element_x.bind('input', oninput)
element_y.bind('input', oninput)
</script>
<input id="input_one"></input>
<input id="input_two"></input>
<input id="output" disabled></input>
</body>
</html>

Translate the text of a textarea and store it in another textarea (without API)

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<textarea id="textetrad" rows="5"></textarea>
<textarea id="translated-text" rows="5"></textarea>
<button id="run-translation" onclick="runTranslation();">Translate</button>
<script>
function runTranslation() {
var data = document.getElementById("textetrad").value;
var trad = LanguageApp.translate(data, 'en', 'es');
document.getElementById("translated-text").value = trad;
}
</script>
</body>
</html>
Hello, I am creating a bar lateral and I have a problem. I would like to create a textarea where we insert what we want and it is translated in another textarea. I have tried different methods like LanguageApp.translate(data , 'en', 'es') but I can't get this function to work in the HTML code.
So already is what I want possible without using an API?
If yes, should I do it only in the HTML code or should I make the HMTL code and the .gs communicate?
And then how do I transmit the translation from the gs code to the HTML?
I tried and made it work on apps script using LanguageApp
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
</head>
<script type="text/javascript">
function runTranslation() {
google.script.run.withSuccessHandler(onSuccess).translate(document.getElementById('textetrad').value);
}
function onSuccess(data) {
document.getElementById('translated-text').value = data;
}
</script>
<body>
<textarea id="textetrad" rows="5"></textarea>
<textarea id="translated-text" rows="5"></textarea>
<button id="run-translation" onclick="runTranslation();">Translate</button>
</body>
</html>
Code.gs:
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
function translate(textValue){
// automatically identify the language, then translate to spanish
return LanguageApp.translate(textValue, '', 'es');
}
Process:
upon onclick, execute runTranslation.
when translate function (in Code.gs) runs with no issue, proceed with onSuccess
passing the translated data, assign it to the other element
Output:
Reference:
HTML Service: Communicate with Server Functions

WebBrowser not running javascript

I'm utilizing a System.Windows.Forms.WebBrowser (used in a separate .dll file) from my WPF application in order to print some HTML content in the background.
My problem is that the HTML elemnts are not being affected by the javascript in the page.
I know that there are no errors in the page because that if I copy its content after the DocumentCompleted event and paste it into a plain HTML file the script works.
My HTML template:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script>
function loaded() {
document.getElementById("content").innerHTML = "after javascript";
}
</script>
</head>
<body onload="loaded()">
<h1 id="content">before javascript</h1> <!--<= This value does not change-->
</body>
</html>
I use this HTML as follows:
private void PrintTest()
{
string curDir = Directory.GetCurrentDirectory();
string fullPath = Path.Combine(curDir, "PrintDocs\\HTMLPage1.html");
string html = File.ReadAllText(fullPath);
HtmlPrint.Print(html);
}
public static class HtmlPrint
{
public static void Print(string html, string documentTitle = "")
{
var wb = new System.Windows.Forms.WebBrowser { DocumentText = html };
wb.DocumentCompleted += wb_DocumentCompleted;
}
private static void wb_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
var wb = ((System.Windows.Forms.WebBrowser)sender);
wb.Print();
wb.Dispose();
}
}
What am I missing here?
You forgot the Braces in onload:
<body onload="loaded()">
As mentioned in my comments you can call the InvokeScript() method from your C# code and pass in your js function name as which should do the trick.
wb.Document.InvokeScript("loaded");
I think you have to change onload="loaded" to onload="loaded()"

Javascript error: function XXXX() not defined

I added a javascript function in a page
<head>
<script type=text/javascript>
function show_Alert(error)
{
alert(error);
}
</script>
</head>
and on button click I am doing this
Protected void btn_Click(object o,Eventargs e)
{
StringBuilder str = new StringBuilder();
str.AppendLine("show_Alert('XYZ error')");
ClientScript.RegisterStartupScript(GetType(),"Alert",str.ToString(),true);
}
But it throws JS error show_Alert is not defined :(
Any Idea, what is wrong here??
Thanx
Your script tag is wrong.
Change it to
<script type="text/javascript">
However, I don't think that's the issue.
I suspect that RegisterStartupScript is emitting its <script> block before the one with your function, so that it ends up calling the function before it exists.
Check where each <script> is in the rendered source.
Make sure your <script> element is valid, like this:
<head>
<script type="text/javascript">
function show_Alert(error)
{
alert(error);
}
</script>
</head>
If it's not well formed, or the type is unrecognized (your case has both) then the script inside will be ignored, since the browser doesn't know how to handle it.
Here's an example:
<%# Page Language="C#" %>
<script type="text/C#" runat="server">
protected void BtnClick(object sender, EventArgs e)
{
var str = "XYZ Error";
var script = new StringBuilder();
script.AppendFormat("showAlert('{0}');",
HttpUtility.JavaScriptStringEncode(str)
);
ClientScript.RegisterStartupScript(GetType(), "alert", script.ToString(), true);
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function showAlert(error) {
alert(error);
}
</script>
</head>
<body>
<form id="Form1" runat="server">
<asp:LinkButton ID="Btn" runat="server" Text="Click me" OnClick="BtnClick" />
</form>
</body>
</html>
A very important thing to pay attention to is to properly encode the string you are passing to the showAlert function. Notice that it is encoded:
script.AppendFormat("showAlert('{0}');",
HttpUtility.JavaScriptStringEncode(str)
);
If you don't encode it and the string contains some special characters like ' for instance, your script will break.

How to call Onload function in the Main page as well as #include file inner.jsp page

I have two pages one is the main page and the another one is the inner page:
Page names: main.jsp , sidebar.jsp
I want to call the onload function on both of these pages. Is that possible. If yes How?
Below is the code for main.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# include file="/pages/common/init.jsp"%>
<%# taglib prefix="sx" uri="/struts-dojo-tags"%>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>J.C. Taylor - Broker Website</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<link rel="stylesheet" href="/css/default.css" media="screen" type="text/css" />
</head>
<body onload="prepopulateFields();load(17);">
<s:form name="continue" id="continue_id" action="continue" method="POST" validate="true" enctype="multipart/form-data">
<div id="wrapper">
<div id="main">
<div id="sidebar">
<%# include file="/pages/common/sidebar.jsp"%>
<span class="clearIt"></span>
</div>
The sidebar.jsp is:
<body onload="setSelected();">
//Some static content here
</body>
So Basically I want is to call prepopulateFields() Javascript method which belongs to onload() event of the main .jsp page and setSelected() which belongs to onload() method of the sidebar.jsp symulatneously and separately.
I know I can call the setSelected(); method inside the prepopulateFields() method but that I dont want to do. All I want is when the page is loaded both the onload functions should be called separately.
If you have some suggestions please do let me know!
I know I am being little bit ridiculous here but if I could do that My job will be very easy.
i don't think you can call more than one onload function.
best way is to call the method from already called function
function prepopulateFields(){
if //condition which check the current page where you want other onload function
setSelected();
}
<body onload="prepopulateFields();load(17);">
</body>
You cannot nest HTML <body> elements, it would only malform HTML.
Best is to put it as a <script> at the bottom of sidebar.jsp.
<script type="text/javascript">setSelected()</script>
If you use firebug to inspect the rendered html page of main.jsp. You would see there is only one < body > element. The < body > element in your sidebar.jsp is not rendered since it will malform HTML as html or body not allowed in included jsp.
Be careful that the included file does not contain <html>, </html>, <body>, or </body> tags
The solution is:
either put your setSelected() into main.jsp body onload event if the sidebar.jsp is always loaded;
or do as BalusC suggested.
window.onload = codeAddress; should work. Here's a demo. And the full code:
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
Put the class definition in the parent jsp, and instantiate as many onloads as you need in the includes.
<SCRIPT>
// this portion was placed above the Class definition for convenience.
// make sure the Class definition gets loaded first in your code.
new OnLoad(function(){
alert("document loaded");
},100);
</SCRIPT>
...
<SCRIPT>
// Class Definition
OnLoad = function(taskFunction,miliseconds) {
var context = this;
context.cnt = 0;
context.id = null;
context.doTask=taskFunction;
context.interval = function() {
if(document.readyState == "complete"){
try{ context.stop();} catch(e){ throw new Error("stop error: " + context.id); }
try{ context.doTask();} catch(e){ throw new Error("load error: " + context.id); }
}
};
context.start = function(timing) {
if(context.id && context.id!=null)
context.stop();
context.cnt=0;
context.id=setInterval(context.interval,timing);
};
context.stop = function() {
var _id = context.id;
clearInterval(context.id);
context.id=null;
};
context.start(miliseconds ? miliseconds : 100);
};
</SCRIPT>

Categories