javascript function not getting executed - java

I want to execute a javascript function in an external js file when the page is loaded. This is the code in the jsp file where the function is called from, I placed it at the bottom of the jsp
<%-- Begins countdown --%>
<script src="/pub/scripts/counter.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload=startCountdown;
</script>
this is the function in the js file
function startCountdown() {
var TIMEOUT = 900000;
var COUNT_BACK = 3;
setTimeout("displayWarning("+COUNT_BACK+")", TIMEOUT);
}
when the page loads in the browser I see that the script is loaded but the startCountdown function never gets executed. How can I make this work?

I would use <body onload="startCountdown()"> in your html to ensure that the page must load completely before executing the script.

Change window.onload=startCountdown; to window.onload=startCountdown(); and use defer
<%-- Begins countdown --%>
<script defer src="/pub/scripts/counter.js" type="text/javascript"></script>
<script defer type="text/javascript">
window.onload=startCountdown();
</script>
this is the function in the js file
var startCountdown = function() {
var TIMEOUT = 900000;
var COUNT_BACK = 3;
setTimeout("displayWarning("+COUNT_BACK+")", TIMEOUT);
};

Related

java controller to html if alert

i have a problem using alert in html.
I have a controller in Java that sends
model.addAttribute("borrowedAlready",1);
and I need to take it from html.
here's code i have but doesn't seem to work.
<div>
<script type="text/javascript">
var borrowed = '${borrowedAlready}';
if(borrowed== 1){
alert("Borrwed Already.");
}
</script>
</div>
Need help

getting an immediate redirect. Why is this so?

I am trying to redirect the user from one jsp page to another jsp page after making him wait for 10 seconds or 10000 milliseconds. But there is a redirect as soon as the page is opened in the browser. Why is this is so ? Is there anything wrong in the following code ? I am calling the redirectFunction which does the redirect.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP - 1</title>
<script>
function redirectFunction() {
<% response.sendRedirect("jsp-2.jsp"); %>
}
</script>
</head>
<body>
<h1>
Wait while you are redirected...
</h1>
<script type="text/javascript">
setTimeout(redirectFunc,10000); // wait for 10 seconds,then call redirectFunc
</script>
</body>
You sends redirect exactly from server that`s why it fired immediatelly.
If you want to fire redirect after 10 seconds than you need to change your code:
function redirectFunction() {
window.location.href = "jsp-2.jsp"
}
and setTimeout(redirectFunction,10000);
Actually when you call <% response.sendRedirect("jsp-2.jsp"); %> Java server sets http code 302 to your http response, and header Location: jsp-2.jsp
And browser redirects to page specified in Location header immediately.
Hope it helps.
the code in scriptlet is executed on the server, it is not javascript. use this
function redirectFunction() {
window.location.href = "jsp-2.jsp";
}
Assuming you're using HttpServletResponse, what's happening is that you're sending the HTTP location header with a status code 302. This happens when the page is requested, not during client-side execution of the JavaScript.
If you want it to be during JavaScript execution you need to assign the URL you want to window.location.
window.location = "http://google.com";
for example
This is because
<script>
function redirectFunction() {
<% response.sendRedirect("jsp-2.jsp"); %>
}
</script>
is translated and executed as
out.print(" <script> function redirectFunction() {");
response.sendRedirect("jsp-2.jsp");
out.print("</script>");
The call sendRedirect is executed on the server side, while preparing your page, and it's performing the redirect. You can do the sleep and the redirect in javascript only, using window.location.

Problem with jquery and IE 8 and later

In Firefox work, but when load page in IE8 i get only blank page and source HTML-code available.
I delete
<script src="/NewsManager/js/jquery.js"
type = "text/javascript"
</script>
and all work without script.
NetBeans 6.7, ApacheTomcat, JSP
You missed the closing > in second line:
<script src="/NewsManager/js/jquery.js"
type = "text/javascript"> <!-- close the opening script tag HERE -->
Try this:
<script src="/NewsManager/js/jquery.js" type="text/javascript"></script>

instantiate an object within javascript

**<%# page import="com.ampliflex.commons.Ampliflex" %>**
<html>
<head>
<title>Search Result </title>
<style>
img{ height: 150px; float: left; border: 3;}
div{font-size:10pt; margin-right:150px;
margin-left:150px; }
</style>
<script type="text/javascript" src="jquery-1.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
**Ampliflex ms = Ampliflex.getInstance();
String mailHost = ms.getMailServer();**
// This function get the search results from Solr server
$("#submit").click(function(){
var query=getquerystring() ; //get the query string entered by user
Here in this, I imported a java class and instantiate its object. but object is not visible and script is generating an error "missing ; before statement
Ampliflex ms = Ampliflex.getInstance(); "...i am not getting why so.
EDIT:
The problem is i need to access this mailHost with in javascript. if i instantiate object with in <%.. %> then mailHost is local variable and am not able to access in javascript tag. is there any solution for it.
You are trying to instantiate java object but, without a scriptlet
it should be some thing like
<%
Ampliflex ms = Ampliflex.getInstance();
String mailHost = ms.getMailServer();
%>
$(document).ready(function(){
//Mail host
var mailHost='<%= mailHost %>';
// This function get the search results from Solr server
$("#submit").click(function(){
var query=getquerystring() ;
And, if you want to invoke method after page is loaded, try using ajax.
Problem here is this line:
Ampliflex ms = Ampliflex.getInstance();
String mailHost = ms.getMailServer();
This is actually Java code. This cannot execute on client side. Use scriptlet tags.

Reading a JSP variable from JavaScript

How can I read/access a JSP variable from JavaScript?
alert("${variable}");
or
alert("<%=var%>");
or full example
<html>
<head>
<script language="javascript">
function access(){
<% String str="Hello World"; %>
var s="<%=str%>";
alert(s);
}
</script>
</head>
<body onload="access()">
</body>
</html>
Note: sanitize the input before rendering it, it may open whole lot of XSS possibilities
The cleanest way, as far as I know:
add your JSP variable to an HTML element's data-* attribute
then read this value via Javascript when required
My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.
The HTML part without JSP:
<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
Here is your regular page main content
</body>
The HTML part when using JSP:
<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
Here is your regular page main content
</body>
The javascript part (using jQuery for simplicity):
<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
jQuery(function(){
var valuePassedFromJSP = $("body").attr("data-customvalueone");
var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");
alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>
And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/
Resources:
HTML 5 data-* attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Include javascript into html file Include JavaScript file in HTML won't work as <script .... />
CSS selectors (also usable when selecting via jQuery) https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors
Get an HTML element attribute via jQuery http://api.jquery.com/attr/
Assuming you are talking about JavaScript in an HTML document.
You can't do this directly since, as far as the JSP is concerned, it is outputting text, and as far as the page is concerned, it is just getting an HTML document.
You have to generate JavaScript code to instantiate the variable, taking care to escape any characters with special meaning in JS. If you just dump the data (as proposed by some other answers) you will find it falling over when the data contains new lines, quote characters and so on.
The simplest way to do this is to use a JSON library (there are a bunch listed at the bottom of http://json.org/ ) and then have the JSP output:
<script type="text/javascript">
var myObject = <%= the string output by the JSON library %>;
</script>
This will give you an object that you can access like:
myObject.someProperty
in the JS.
<% String s="Hi"; %>
var v ="<%=s%>";
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
<title>JSP Page</title>
<script>
$(document).ready(function(){
<% String name = "phuongmychi.github.io" ;%> // jsp vari
var name = "<%=name %>" // call var to js
$("#id").html(name); //output to html
});
</script>
</head>
<body>
<h1 id='id'>!</h1>
</body>
I know this is an older post, but I have a cleaner solution that I think will solve the XSS issues and keep it simple:
<script>
let myJSVariable = <%= "`" + myJavaVariable.replace("`", "\\`") + "`" %>;
</script>
This makes use of the JS template string's escape functionality and prevents the string from being executed by escaping any backticks contained within the value in Java.
You could easily abstract this out to a utility method for re-use:
public static String escapeStringToJS(String value) {
if (value == null) return "``";
return "`" + value.replace("`", "\\`") + "`";
}
and then in the JSP JS block:
<script>
let myJSVariable = <%= Util.escapeStringToJS(myJavaVariable) %>;
</script>
The result:
<script>
let myJSVariable = `~\`!##$%^&*()-_=+'"|]{[?/>.,<:;`;
</script>
Note: This doesn't take separation of concerns into consideration, but if you're just looking for a simple and quick solution, this may work.
Also, if you can think of any risks to this approach, please let me know.

Categories