I'm currently trying to get the live value of a Java object in Javascript to fill up some progress bar.
Here is the code in the JSP file :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="server_ihm_web.server"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<style>
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar1 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
#myBar2 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
#myBar3 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
</style>
<body>
<h1>JavaScript Progress Bar</h1>
<div id="myProgress">
<div id="myBar1"></div>
</div>
<br>
<div id="myProgress">
<div id="myBar2"></div>
</div>
<br>
<div id="myProgress">
<div id="myBar3"></div>
</div>
<%
server serv = new server();
serv.startServer();
%>
</body>
<button onclick="move()">Click Me</button>
<script>
function move() {
var elem = document.getElementById("myBar1");
var elem2 = document.getElementById("myBar2");
var elem3 = document.getElementById("myBar3");
var id = setInterval(update, 100);
function update() {
elem.style.width = <%=serv.getBar1()%> + '%';
elem2.style.width = <%=serv.getBar2()%> + '%';
elem3.style.width = <%=serv.getBar3()%> + '%';
}
}
</script>
</html>
serv values are updated every few seconds but nothing changes for the progress bar.
I think it always take the base value of the object so everytime update() is called it will change the progress bar to the same value.
Is there a way to update the values of serv for the javascript ?
I think you are mixing things that live on separate dimensions :)
Javascript executes in the browser and JAVA (JSP) on the server.
If your ideas was to have the jsp scriptlet execute in the user's browser, it is not going to happen.
If you need to update the page with a progress when it is already in the user's browser, you will have to implement some ajax call to get the updates on the background.
The JSP tags <%= ... %> are evaluated in the server, before the page is displayed the first time in a browser. So, the values of that tags are static, and don't change in each execution of the javascript functions.
For that values to change, you need to do a request to the server, and reload the page. To avoid reloading an entire page each time, you need to do an Ajax request to obtain a new value to display with Javascript.
Related
I'm having a page with some inline css & javascript, the javascript on the original page contains some click and scroll logic which looks like this
$('#abc').on('click', function() {
$('html, body').scrollTop($('#xyz').offset().top)
});
it works fine on the original page;
Now I'm having a new page, which imports the original page as an iframe on the new page, but because it is iframe, the scope of the javascript code on original page inside this iframe is now bind to the iframe itself, and because it's bind to iframe itself, the $('html, body').scrollTop no longer works...
Is there anyway I can modify the original page to make it work through iframe?
for obvious security reasons, iframes are isolated in their own sandbox.
however, if you are in control of the code of the parent page and the iframe page, then you can use the message mechanism and pass your information through the event.data part.
here the example only passes text, for more extensive data, use JSON.stringify () / JSON.parse ()
file z1.html (parent)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Z1</title>
<style>
#iFrameZ2 { width: 400px; height: 150px; border: 1px solid red; }
#receiveTxt { margin: .5em; border: 1px solid blue; padding: .2em; width: 15em; }
</style>
</head>
<body>
<h4>main page (z1.html)</h4>
<input type="text" id="messageTxt" placeholder="a message...">
<button id="btSender">send to iframe</button>
<div id="receiveTxt">.</div>
<br> <br> iframe:<br>
<iframe id="iFrameZ2" src="z2.html" frameborder="0"></iframe>
<script>
window.onmessage = e =>
{
receiveTxt.textContent = e.data
/* ----------------------
if (e.data==='scroll')
{
document.querySelector('#xyz').scrollTop
}
------------------ */
}
btSender.onclick = _ =>
{
let info = messageTxt.value.trim()
if (info!='')
iFrameZ2.contentWindow.postMessage( info,'*')
}
</script>
</body>
</html>
file z2.html (iframe)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h6>z2.html</h6>
<input id="msgTxt" type="text" placeholder="send a message">
<button id="btSender">send msg</button>
<p id="getMsg">...</p>
<script>
btSender.onclick=_=>
{
let info = msgTxt.value.trim()
if (info!='')
window.parent.postMessage(info,'*')
}
window.onmessage = e =>
{
getMsg.textContent = e.data
}
</script>
</body>
</html>
My WebApp URL is this:
https://script.google.com/macros/s/[Deployment ID]/exec
It shows the form correctly. I have a button on top of this form to come back to home page. It only has to add ?page=home to the above url. But when I click that button URL is shown as following:
https://n-f22j6yycycwkqttwlgfk5eezyixnbwfyfih4bba-0lu-script.googleusercontent.com/userCodeAppPanel?page=home
So last parameter part is what I have expected with my webapp url, not with this:
...script.googleusercontent.com/userCodeAppPanel
which I do not understand so far.
What is userCodeAppPanel?
How to solve this problem?
I tried to create sample project for similar webapp with only three pages. But when I deployed I get other problem - not the above one. So I guess the question also should be changed now.I did change the question.
New question is : Google WebApp URL if changed manually is working but via button href not working. Why?
GS doGet function:
Within doGet i have following -
var html = doGetPageOrIndex(e);
return html;
function doGetPageOrIndex(e){
var page = e.parameter.page
return HtmlService.createHtmlOutputFromFile(page || 'index2')
.addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setTitle('App Demo')
}
HTML page1
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h3>Heading Page 1</h3>
<p>Thanks Man</p>
</body>
</html>
HTML page2
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h4>Your Page2</h4>
<p>You are welcome!</p>
</body>
</html>
This demo is being copied from another user of stackoverflow.
here is Index2 HTML page code:
<!DOCTYPE html>
<html>
<head>
<base target="_top" />
<title>Single Page App</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
h1 {
text-align: center;
margin: 2px;
text-transform: uppercase;
background-color: blue;
}
span:hover,
a:hover {
background-color: yellowgreen;
}
body {
background-color: brown;
color: white;
font-size: 2em;
}
a:visited {
color: white;
}
</style>
</head>
<body>
<h1><span id="type">Multi</span> Page App </h1>
<div id="main">Loading...</div>
<script>
//Change base url
google.script.run
.withSuccessHandler(url => {
$('base').attr('href', url)
})
.getUrl()
//Function to handle hash change
function change(e) {
let hash = e.location.hash
if (!hash) {
main()
return
}
google.script.run
.withSuccessHandler(htmlFragment => {
$('#main').html(htmlFragment)
})
.getHtml(hash)
}
google.script.history.setChangeHandler(change)
//Function to add Main page html
function main() {
$('#main').html(`
<ul>
<li>Page1</li>
<li>Page2</li>
</ul>`)
}
//Loads Main html from main function
//Adds toggle to span to change to a Multiple page app
$(() => {
main()
$('#type').on('click', () => {
let hf = $('a').attr('href')
if (!hf) return
hf = hf.indexOf('#') + 1
$('#type').text(hf ? 'Multiple' : 'Single')
$('a').each((i, el) => {
$(el).attr('href', (i, v) =>
hf ? '?page=' + v.slice(1) : '#' + v.slice(6)
)
})
})
})
</script>
</body>
</html>
If I edit the URL manually and use following and then enter - I will get target page without problem.
https://script.google.com/a/macros/5times.co.in/s/AKfycbyY7gR13A1C7a7SVtbYnCy_2TiMeeZWM1ggW134GMKTHOwLvjfnJsGEmtzSgYQmLLIsbQ/exec#page2
But If I use the home page and then click page1 or page2 link then nothing happen to the page. Even though the URL is correctly changed as expected. This is confusing to me. If I edit the URL again and change page1 to page2 and then enter it will work. So why it is not loading page1/2 when I click the page1/2 link on main page?
All the codes are copied above. Thank for your effort in advance.
I would like to get the current logged in username and display it my frontend.
Currently I have a function called GetCurrentUser() that gets called when a button is clicked.
<button type="submit" onclick="GetCurrentUser()" style="margin-left: 15px;margin-top:10px; margin-bottom: 5px;background-color: black; "value="Submit">Save Selections</button><br>
function GetCurrentUser() {
var usrName ="#HttpContext.Current.User.Identity.Name.ToString()";
//var usrName = '<%HttpContext.Current.User.Identity.Name %>';
//document.getElementById("UserName").innerHTML = usrName;
console.log(usrName);}
I get the follwoingoutput in my console log--> #HttpContext.Current.User.Identity.Name
If you are seeing the literal output of "HttpContext.Current.User.Identity.Name " then your JS function is generated client side after you have lost server context.
Couple options for you:
Call back to your controller via ajax to get the username
Store the username in a read only field on page load (kinda like setting a form value) and retrieve the value via jquery or js on function call
Assign the username on page load to a global js element and just use that element in your function.
Here is an example of 2 and 3. I don't think you should worry about #1 until you fully understand why your issue is happening in the first place:
<div class="btn btn-info" onclick="GetCurrentUser()" style="margin-left: 15px;margin-top:10px; margin-bottom: 5px;background-color: black; " value="Submit">Save Selections</div><br>
<input type="hidden" name="method2" id="method2" value="#System.Security.Principal.WindowsIdentity.GetCurrent().Name">
#section scripts {
<script>
var globalSettingMethod = '#System.Security.Principal.WindowsIdentity.GetCurrent().Name';
function GetCurrentUser() {
alert(globalSettingMethod);
alert($('#method2').val());
}
</script>
}
I could get the user logged in by passing the script at the end of the document.
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="Example.SiteMaster" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form runat="server">
</form>
<script>
var loggedUser = "<%: HttpContext.Current.User.Identity.Name %>";
</script>
</body>
</html>
I hope you find it useful.
I am trying to get the content of a JSP using AJAX, fill the page with some additional data (the content object), and then load the full page I get on a new window:
JavaScript:
var request = $.ajax({
type: 'POST',
url: ctx + "/model/nbReport.jsp",
dataType: 'html',
data: {content: content}
});
request.done(function(data) {
var reportWindow = window.open();
$(reportWindow.document).html(data);
});
This is the JSP:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<style type="text/css" media="all">
#page {
size: A4 portrait; /* can use also 'landscape' for orientation */
margin-top: 3.0in;
margin-bottom: 1.0in;
#bottom-center {
content: element(footer);
}
#top-center {
content: element(header);
}
}
#page-header {
display: block;
position: running(header);
}
#page-footer {
display: block;
position: running(footer);
}
</style>
</head>
<body>
<div id="page-header">
</div>
<div id="page-footer">
</div>
<div id="page-content">
${param.content }
</div>
</body>
</html>
The .done() callback is never executed. I tried also to implement a .always() and it is not run as well. Actually if I check the request object it has readyState=1, that should mean that the post was never completed. But actually checking on the firebug console the POST appears to be successful.
The response of the post is the HTML contained inside the JSP. No error is reported in the logs.
Does anybody know how could I solve this empasse?
What I aim to do is to get the page "/model/nbReport.jsp", populate it with the data contained in content (which is just a list of HTML tags dynamically created) and open the filled page in a new window.
All
<input type ="button" value ="test" onClick="SelectAll(this.form);" />
<script ......>
function SelectAll(form)
{
alert(form);
}
</script>
method 1 produce an alert message 'undefined' while 2 method works fine by displaying form object . I'm very much aware that anchor elements don't have a form property, that references the form , unlike input elements,but is there any alternative way to pass form object using hyperlink or is there any way to style the button to look like an hyperlink
Thanks
Try this...
onClick="SelectAll(getParentForm(this));"
function getParentForm(el) {
while(el = el.parentNode) {
if(el.tagName.toLowerCase() === "form")
return el;
}
return null;
}
Since the anchor is not a form control, it doesn't have a form property. You would need to find some other way to reference the form (or stick to a button, which is the right choice of control for something like this).
Honestly? I think your best approach is to not use an anchor element at all. It's not really a link, so that's actually a misuse of HTML.
Use a button element instead, which does have a form property. If you really want it to look like a link, slap on a little CSS to make it look like one.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
button.link {
border: none;
background-color: transparent;
color: blue;
margin: 0;
padding: 0;
cursor: pointer;
text-decoration: underline;
}
</style>
<script type="text/javascript">
function SelectAll( f )
{
alert( f );
}
</script>
</head>
<body>
<form id="test">
<button class="link" onclick="SelectAll(this.form)">All</button>
</form>
</body>
But there are probably a dozen other ways to get a reference to the form element itself. If your form definition looked like this
<form id="test" name="tester">
and it's the only form on the page, here are some ways to obtain a reference to it
document.forms.tester
document.forms['tester']
document.forms[0]
document.getElementById( 'test' )