How to load javascript function after a servlet loads page using PrintWriter - javascript

I've been searching and I can't find an answer to this.
I'm using Servlet and after the servlet loads, I'm printing using response.getWriter().print(String); in the web. When all the content in the web browser is loaded I want to execute a Javascript script but I can't make it runs.
Any idea how can make it run?

Using response.getWriter().print(String) is very primitive way of generating HTML from servlet. Your best bet is to use JSP or JSF for that purpose. But to answer to your original question you either need to write the raw Javascript code or Javascript import along with onload right into the string that you pass to print method. See this HTML snippet for example how that string should look like:
<body onload="doSomething()">
<script>
function doSomething() {
}
</script>

Related

Get return value from JS code to C#

I want to get the answer of a window.prompt() alert box through the C# Code Behind file. It's just a one-liner of JavaScript code, so I thought I could even execute it from the Code Behind file. It doesn't really matter to me whether it's a <script> tag in the .aspx file or executed through the .aspx.cs file.
I thought of having the script executed (called from the C# part) and then having the return value assigned to a certain not visible field, but is there any better way to do it?
The obvious way would probably go something like this:
.aspx file:
<script>
function foo() {
document.getElementById('MyFieldID').value = window.prompt('Answer this question:', '');
}
</script>
.aspx.cs file:
////////////////////////////////////////////////
//MyFieldID.Text now contains whatever I want//
//////////////////////////////////////////////
What do you say? Is there any better way?
Better way is always opinion based. What I'd say is you have a few options, all depend on what you're doing. HTTP and ASP.NET provide us a few means of sending data to the server, there are 3 main ones before HTML5:
Query string
Form values
AJAX calls
If you're redirecting the user to a new page after they answer the prompt, you can just send them to yournewurl.aspx?promptAnswer=*whatever*
If you're doing a postback, then you can use a form value (this looks like what you're doing in your example). You can put an <asp:HiddenField> on the page and populate it from JavaScript before submitting the form.
If you need just the prompt response, but are not attempting to reload the page, you can make an AJAX call that sends the variable to the server (this still uses #1 or #2 to send the data, it just does it without reloading the page).
Which of those three options works best depends on your implementation. However, your solution should work just fine. However, since the control you'd likely be using to stuff the value into is a HiddenField it would be in MyFieldID.Value not MyFieldID.Text. The only other thing you have to deal with is if your MyFieldID is nested in some other controls (like a ContentPlaceHolder) such that the ClientID has naming containers pretended to it so it's really something like ContentPlanceHolder1_MyFieldID when accessed from JavaScript.

Can I somehow call JSTL function from JavaScript file?

The question is as following: when I write JavaScript inside my JSP page, using JSTL function, it renders normally, understanding everything I want from it. But to make my code clear, I want to move that JavaScript from tag in JSP to a separate file. But when I try to call same function from the file, it doesn't work, but just appends to my page as a simple text.
Here is code example to make this more understandable.
...other JSP stuff
<script>
$.each(data, function(index, item) {
$('#holder').append(
'<tr>' +
'<td>item.price + ' <fmt:message key="currency.default"/></td>'
'</tr>'
);
});
</script>
This works perfect for me. The actual message from the resource bundle is pulled and set instead of the fmt:message function.
But when I move the same code to a separate file, all this doesn't transform and stays plain text.
I understand, that JSP serves on the server, and all transformations with those functions is done much earlier than actual javascript is loaded.
But maybe somebody knows a certain hack to make this work?
Thanks in advance.
You can use DWR for that cause. An old framework but still holds good if that is what exactly you are looking for in your question.
http://directwebremoting.org/dwr/index.html
DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible.
Running java methods or jstl functions(also jstl functions are java methods) from JavaScript is impossible. Because java methods run on server-side but javascript on client-side.
If you want to run java methods in client-side anyway you must create java applet for this. You can run java methods with JavaScript inside your applet. For detailed information see this Java Applet Tutorial
I hope this will help you

Can I load a javascript array from an external file?

My app uses a lookup table that is embedded in the script. For ease of maintenance I would like to load this table from an external file. What is the best way to accomplish this? I am using the table to specify an image to be loaded on a click event.
var categoryTable = {
"volunteer": "d3_files/images/thunderx64.png",
"organization": "d3_files/images/cloudyDayx64.png",
"air":"nothing"
};
you can make a function in other js file that return this array.
load that file and call function to get this array.
An external .js file can contain any valid Javascript. Putting a variable assignment in it is just fine.
It will have to be a global variable for it to be visible to code in other files.
Take a look at jQuery getScript() Method:
Quoting from Jquery site:
Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.
If your table is JS, then this should help you. However, I think that a better approach would be to rewrite the table code and give it a JSON or XML form. It is is table, then it should be adaptable to some standard form of data representation rather than some custom JS code.

Why doesn't embedded JavaScript execute when inserted in response to an ajax call?

Inserting JavaScript in the .innerHTML does not cause it to run.
I have what I call a mini-feed in which a user submits a post. This initiates an ajax call which saves the user data to the mysql table. From there PHP generates the xhtml. From there the the PHP generated xhtml is sent back to javascript as response text. This xhtml contains embedded javascript used to display "pretty time".
Now if the PHP generatd xhtml/javascript is send to the client in a non-ajax way this works. But when I send it as responseText and then update the DOM using .innerHTML it does not function. Whatever mechanism that picks up javacript with in the XHTML does not seem to like the embedded javascript written into the .innerHTML property of the enclosing div tag.
Is there an easy fix for this? Or do I have to construct the UI with in the javascript with out just inserting it all in as innerHTML...in a previous post someone mentioned that .innerHTML was not good practice. Perhaps this is what they meant.
You're right, innerHTML will not do that, if you want to dynamically create a script tag, you will need to use document.createElement to create a script tag, but that has all of the same wonderful security bonuses associated with eval.
Here's another idea, though. Wouldn't it be better to have some function defined in the main page which, after appending anything new, sets the date to "pretty" mode without needing to have the AJAX response know anything about it?
The following code should work:
function onSuccess() {
src = document.createElement('script');
src.innerHTML = this.responseText;
document.body.appendChild(src);
}
But I would agree with cwallenpoole that why not have all that javascript code (for pretty-fying the date) be already written in advanced in the main page? (or script included or something).

Calling Java inside JavaScript Function

Please tell me if we can call java inside javascript function ?
<HTML><HEAD></HEAD><BODY>
<SCRIPT>
function getScreenDimension() {
<% System.out.println("Hiiiiiiiii"); %>
}
</SCRIPT>
<FORM>
<INPUT type="button" value="call Java method direct" onClick = "getScreenDimension()">
</FORM>
</BODY></HTML>
While the answer of "No" is technically correct based on the phrasing of the question. You may want to read up on AJAX. It is a way for javascript to make a request to your backend code (in this case Java).
Javascript is client side, meaning it is run by the user's browser. Java is running on your server. In order for the client side javascript to interact with the backend Java, you need to make a request to the server.
My question to you would be, "What are you trying to do, and what do you expect to see?".
You have to realize that there are two different execution contexts. The first is the JSP itself whose code is executed by the JVM on the server-side, and the second is the Javascript that is executed by the browser. So when the code goes to the browser, you'll see: So the System.out.println will cause Hiiiiiiiii to be printed to the server logs, but you won't see anything on the browser. In fact, the Javascript code on the browser will look like this:
function getScreenDimension() {
}
Which is not valid Javascript code. The code in the JSP is run before the Javascript gets run on the browser. So to "run" Java code, you need to make a request to your server either by posting the form or with an AJAX call. This will cause Java code in the appropriate servlet or controller, to run.
UPDATE
After glancing at your code, it appears that you want to call a Java method directly. This is not possible with your current code. You might want to read up on AJAX. This will point you in the right direction.
JSP runs on the server. It generates a document which the server sends to the browser. That is the end of the involvement of JSP in the process. The browser then parses the document and runs any JS.
You can include JSP in a script element, it just has to output valid JavaScript.
You cannot have JSP that runs in response to JavaScript, other then when JavaScript causes the browser to issue a new HTTP request (either setting location.href, submitting a form, adding an image, or using Ajax, etc)
I think you have lack of understanding of what is going on here. Anything in middle of <% %> is executed when the page is first requested. Anything in javascript is executed when the browser calls it. What you have will never happen and there is no way to make it happen. However, you can use AJAX to do something like this but that's a different question.
Yes, you can. Use JSP expressions <%= %>. Example:
<aui:script use="aui-datepicker">
AUI().use('aui-datepicker', function(A) {
new A.DatePickerSelect({
calendar : {
dates : [ '<%="1/1/1970" %>' ],
}
}).render('#myDatePicker');
});
</aui:script>
Yes, you can call Java from Javascript, both if you mean the Java-VM on the server and on the client; i assume you mean the client (the VM in the browser); take a look here:
http://www.apl.jhu.edu/~hall/java/Java-from-JavaScript.html
You can. In JSF you can use PrimeFaces' component p:remoteCommand, which would contain action method. Call that remoteCommand by its name from JS and the java method will get executed.
JSF Page
<p:remoteCommand name='rmt' action="#{bean.doWork()}"/>
In JavaScript
function callJava {rmt();}
Use JSP code
<%
// Respond to the application with 1) result, 2) update, and 3) updateid values
String result = "blablabla";
out.print(result);
%>

Categories