I want to use a Javascript variable in JSP scriplet of the same page. See example below.
<script language="javascript">
var i=10;
</script >
< % out.println(i); % >
It should print the value of i defined in script tag above. Both script and scriplet are part of the same .jsp page
<div id='out'>
<div>
<script language="javascript">
var i=10;
document.getElementById('out').innerHTML = i ;
</script >
It is not really an answer , because your problem is irrelevant. There is a difference between what gets executed serverside and clientside , and your javascript will get executed clientside , the jsp tags on the server , etc... Either you define and display i in java , or in javascript.
Related
I am developing page builder widget. I have to save entire html of edited page to local storage and database. PHP script will load saved html from database, and javascript would save it to local storage, and page builder widget script will parse html saved in local storage.
The problem is that when the html includes <script></script> tag, it won't load successfully. For example, the following script will show error, if html includes script tag.
<script>
<?php $html = $db->getPageHtml();?>
window.localStorage.setItem('pb_html', `<?php echo $html?>`);
</script>
For example, if $html is set as </script> the following script will show error:
<script>
window.localStorage.setItem('test', `</script>`);
</script>
The other html tags are successfully rendered. I think </script> take priority than ` (backtick) when javascript is parsed by browser.
PHP function htmlspecialchar won't solve this problem because it converts < and > to < and >. And page builder javascript don't understand it. Do you have any suggestion?
Browsers generally don't parse the script when looking for the </script> tag. First they extract everything between <script> and </script>, then this is parsed as JavaScript. It doesn't matter what type of quotes are used around the tag, since it isn't parsed at that point.
The usual way to avoid problems when you have a literal string containing </script> is to split it up.
window.localStorage.setItem('test', `</sc` + `ript>`);
See Why split the <script> tag when writing it with document.write()?
My knowledge of javascript is medium, sorry if this question seem too newbie
I call a (stripe) script to display the checkout, my 'desc' variable, which is properly in my page, is just not used in the tag. Instead I have 'desc'.
data-description='bonjour' works
var desc = 'bonjour'
data-description=desc does not work
what am I missing here ?
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key=""
data-amount=amount
data-name="<%= current_user.full_name %>"
data-description=desc
data-panel-label="Encaisser"
data-label="Payer par carte"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="fr"
data-currency="eur">
</script>
You don't actually have any Javascript there - what you have is only HTML markup, describing a script tag and its HTML attributes, so you can't use var or anything else particular to Javascript.
<script no javascript here because this is HTML, not JS>
JS can only be used here, in the content of the script tag
</script>
This question already has answers here:
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
(5 answers)
Closed 4 years ago.
I have a JSP page called index.jsp. I have a Java variable called totalCount inside this page :
<%= int totalCount = getTotalCount();%>
Now I want to use this variable in Javascript section to generate a chart:
<script type="text/javascript">
</script>
How can I pass this Java variable inside ? Thanks.
Just assign the value to your Javascript variable.
<script type="text/javascript">
var count = '<%= totalCount %>';
</script>
But using scriptlets been highly discouraged and shift to JSTL as soon as possible.
Read : How to avoid Java code in JSP files?
As others pointed out, do not create unnecessary hidden elements on DOM. If you really want to use this variable across files declare this variable on top. Even before script includes, so that it avail across all the files.
Example:
<script type="text/javascript">
var count = '<%= totalCount %>';
</script>
<script type='text/javascript' src='js/blah.js'></script>
<script type='text/javascript' src='js/blahblah.js'></script>
Just create a hidden field on your HTML page and access that value using JavaScript.
HTML
<input id='hdn-total-count' type='hidden' value='<%=totalCount%>' />
JavaScript
var totalCount = document.getElementById('hdn-total-count').value;
jQuery (Cross browser compatible)
var totalCount = $('#hdn-total-count').val();
All of the other answers are going to work on inline and on-page JavaScript. But they are not going to work for JavaScript in external files (which are cacheable).
simply you can use
<script type="text/javascript">
var xyz=<%= getTotalCount();%>
</script>
But I dont recommend you to use java codes inside JSP.Please look for JSTL
you can write a code something like this. But it's not a clean way of doing it. Why do you want to do it? You can do it via AJAX calls.
Here is the sample code
<sciprt type="text/javascript">
var myVariable = <%=request.getAttribute("rep");%>
</script>
I have a small chunk of code I can't seem to get working. I am building a website and using JavaScript for the first time. I have my JavaScript code in an external file 'Marq_Msg.js' which looks like this:
var Messages = new Array();
Messages[0] = "This is message 1";
Messages[1] = "This is message 2";
Messages[2] = "This is message 3";
Messages[3] = "This is message 4";
function scroll_messages()
{
for (var i = 0; i < Messages.length; i++)
document.write(Message[i]);
}
and in my HTML file 'Index.html' I am trying to call it like this:
<div id="logo">
<marquee scrollamount="5" direction="left" loop="true" height="100%" width="100%">
<strong><font color="white"><script src="Marq_Msg.js">scroll_messages()</script></font></strong>
</marquee>
</div>
The 'logo' div is a CSS piece that I'm trying to marquee inside of. If I put the code embedded inside the 'head' tag and call it, it works perfectly! There are a few other things id like to do with this code (like space the messages out a little) but I can't get the code to work in the first place. I've also tried adding:
<script src="Marq_Msg.js"></script>
in the 'head' tag with a separate call, that was a no go. I also tried instead using:
<script type="text/javascript" src="Marq_Msg.js">scroll_messages()</script>
Hell, i even had the function try returning a string (even hardcoded a simple "hello" to be returned) but that didnt work either with and without the 'type':
//Marq_Msg.js
function scroll_messages()
{
return "hello";
}
//index.html
<script type="text/javascript" src="Marq_Msg.js">document.write(scroll_messages())</script>
What am I missing? Any help would be greatly appreciated!! I've looked all over Google, and every site I find wants to do it using some 'form'. I just want messages to be displayed across, no form attached.
If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).
You need to use multiple script elements.
a <script> to load the external script
a <script> to hold your inline code (with the call to the function in the external script)
scroll_messages();
In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page.
Follow the code snippet for insight:-
caller.html
<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">
external.js
function letMeCallYou()
{
alert("Bazinga!!! you called letMeCallYou")
}
Result :
If anyone still has the reference error is probably because you are loading your Javascript with defer, or it's in the bottom of the body so when the function gets called your function still doesn't exist.
I have a JSP page where I am reading Session Attributes that I set in the Session.
I want to read the Session attributes in regular intervals. I don't want to reload the whole page instead I am just keeping my JSP Session read attributes in my DIV and trying to reload the DIV. But it is not reloading the DIV.
Here is my code base:
<html>
<head>
// Loading CSS and Script files
</head>
<body>
<div id="loadData" style='display:none;'>
<%
String strStatus = String.valueOf(session.getAttribute("Status")) ;
%>
</div>
</body>
<script type="text/javascript">
var reqStatus = '<%= strStatus %>';
$(this).load(function(){
setInterval(function() {
$("#loadData").load();
} ,1000);
});
$("#loadData").load(function(){
if(reqStatus == 'Done') {
// My Code goes here..
}
});
</html>
Any better ideas are also welcome.
JSP renders once, on the server, and is then sent to the client, after which the Java code does nothing. You can't put both the HTML/javascript code and the Java code in the same file if you want them to be loaded at different times / frequencies.
Put this into a separate .jsp file:
<%= String.valueOf(session.getAttribute("Status")) ; %>
Assume it's mapped to some url /checkStatus.jsp
Remove the loadData div because you don't need it anymore. Replace your javascript with:
var reloadStatus = function () {
$.ajax("/checkStatus.jsp", function (data) {
if (data == "Done") {
// Your code here
}
});
};
setInterval(reloadStatus, 1000);
Your JSP code is evaluated only once -- when the page first loads. When JSP code runs, HTML is generated and sent to the browser. You cannot "reload" a div like that; the JSP code will not run.
What you can do is put the JSP code into a separate filee and then use jQuery.load to load that page into a div:
jQuery(document).ready(function() {
setInterval(function() {
jQuery('#loadData').load('/status.jsp');
}, 1000);
}
status.jsp will contain just the one line:
<%= String.valueOf(session.getAttribute("Status")) ; %>
The code in a JSP is compiled/executed before the resulting HTML is sent to the browser. You can't reload part of the page as-rendered and expect it to change. You would probably need to make a hidden iframe and reload that completely (easy), or make a webservice to query the params (harder).