Refreshing a DIV element which has JSP code snippet inside - javascript

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).

Related

Execute Javascript only on page load, not PostBack (SharePoint)

I'm trying to execute some JavaScript on page load on a custom page on a SharePoint site (it populates the people picker with the current user). The problem is that the code executes on postback too, which I don't want as it will reset any changes to the people picker.
I've tried using if(!IsPostBack) to no avail. Everything errors out at that point, giving
SCRIPT5009: 'IsPostBack' is undefined.
I can't find anything online to help with this. Any ideas? Thanks
You can create a function like this:
function IsPostBack() {
var ret = '<%= Page.IsPostBack%>' == 'True';
return ret;
}
IsPostBack is not a javascript variable, it's a .NET webforms variable that is only available on the server so the client will complain about it. So what to do then? I suggest this mish-mash in your control's html:
<% if(IsPostBack) { %> <!-- runs on server -->
<script type="text/javascript">
alert('will only be printed to html if not postback');
</script>
<% } %> <!-- ends server if-block -->
You may want to try the below. Use the JavaScript pageLoad method and use the isInAsyncPostBack Property of the PageRequestManager object to determine whether it's a postback. Refer the MSDN link here for more details.
<script type="text/javascript" language="javascript">
function pageLoad(sender, args) {
if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
// call you JavaScript function in here
}
}
</script>

Calling JavaScript function within a JSP page

I am trying to call a in-page JavaScript function from inside a JSP page. Here is the code snippet, but the JavaScript functions are not being called when the JSP page is rendered on the client. Anything wrong following this method of calling?
<% //more jsp code
if(count>0) { response.sendRedirect("main.jsp"); %>
<script type="text/javascript"> setCookie('user','<%=user1%>',1); </script>
<% } else { response.sendRedirect("index.jsp"); %>
<script type="text/javascript"> alert("please enter proper credentials and log in again"); </script>
<% } // more jsp code %>
You are attempting to send an HTTP redirect and output some HTML at the same time.
The HTML will appear on the page that will be displayed to browsers configured to not automatically follow redirects (which is practically none of them) so nobody is going to see the page which includes that HTML.
You need to put the HTML on the page you are redirecting to (or, in the case of the cookie setting code, set the cookie with JSP/HTTP instead of client side JavaScript).

How to call external JavaScript function in HTML

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.

Javascript - Dynamically load a fragment of HTML and run script

I'm building a webpage and I want to re-use some HTML I have elsewhere on my website. The page I am building (index.html) can dynamically get and insert the HTML I want (existing.html) using XMLHttpRequest. However, the HTML I want to get is populated by some Javscript. That Javascript is not being executed when I load it into my new page:
index.html:
<html>
<head>
<script type = "text/javascript">
... //use XMLHttpRequest to load existing.html
initExistingHTML(); //this is function which populates loaded HTML, is not executed
</script>
</head>
<html>
existing.html:
<div>
<script type = "text/javascript">
function initExistingHTML() {
... // do some stuff
}
</script>
</div>
How can I load existing.html and run the script which populates it?
Once the page has loaded, add in existing.html via innerHTML. Rather than calling its functions, just let existing.html's code execute, which will do the same as if it were in the onload section.
EDIT: Or, you could just correct that typo you have. initExistingHTML != initExistingHtml.
lol

How to access javascript variables in dynamically-loaded html page?

I've got a html page which loads another html page into one of its divs via Ajax. Something like:
Base html page:
<html>
<head>
<script type='text/javascript'>
var greeting = "Hello";
</script>
</head>
<body>
<div id="details-main-content">
</div>
</body>
</html>
Page that gets loaded into the one above (uses django templating so whatever is placed in the 'head' block ends up in the 'head' tag of the base page):
{% block head %}
<script type="text/javascript" language="javascript">
alert("Greeting: " + greeting);
</script>
{% endblock %}
<div>
Hello, world!
</div>
The child content gets loaded when a button is clicked, via a Javascript function (using JQuery) such as this:
function loadContent(url) {
// Load external content via AJAX.
$( '.details-main-content' ).load( "/foo.html", function(){
});
}
The page loads correctly, the child content displays exactly desired, inside the templatepage.
Is it possible to access the JS variables in the base page from the inner page (since the inner page is nestled inside of the outer page)?
Any help is greatly appreciated.
Thanks
EDIT:
I think the issue I was having was due to having the following line in the of the base html page:
var gender = null;
var age = null;
Which, each time a new page would be loaded through the load() function, would re-init the variables back to null. Oops
Yes. It's just a single page, before and after the load (which uses XMLHttpRequest). As a simple example, if you had:
var message = "Annoying message";
you could have
Message
in the inner page.
EDIT: If you're having issues, it might be due to the issue noted on the jQuery load documentation:
During this process, browsers often
filter elements from the document such
as <html>, <title>, or <head>
elements. As a result, the elements
retrieved by .load() may not be
exactly the same as if the document
were retrieved directly by the
browser.
There is no "inner" and "outer" page in your example. You just work with single page, some content of which is loaded dynamically, but it is not treated any differently by the browser.

Categories

Resources