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).
Related
I'm trying to create a javascript file with functions that allow me to redirect to another page. But it is not redirected. This is my code:
on my functions.js
function openUrl(url) {
window.location = url;
}
on my php page
<script>openUrl('<?=$my_url?>');</script>
<script src="./functions.js" type="text/javascript"></script>
Order matters
You call openUrl, which (if you have looked at the Console in your browser's developer tools) is throwing a ReferenceError because it isn't defined.
Then you load your functions.js which defines openUrl (but by then it is too late).
That said, if you are generating an HTML document which immediately goes to a new URL with JS then you should probably be simply issuing a 301 or 302 redirect response instead of an HTML document in the first place.
switch these two lines
<script src="./functions.js" type="text/javascript"></script>
<script>openUrl('<?=$my_url?>');</script>
I am building a simple asp.net application and in my aspx page I want to reference a script with dynamic query parameter.
For example:
<script src="../javascript/script.js?v=#var#" type="text/javascript"></script>
In the above code script path can have different query parameter in place of #var#.
I have also tried following code to get the parameter value from code behind.
<script src="../javascript/script.js?v=<%# myVar %>" type="text/javascript"></script>
but, here <%# myVar %> returns blank value. If I use = instead of # then it works perfectly if I add the script reference at the bottom of the page.
But, it only works if I reference the script at the bottom of page. otherwise it will throw the error.
"The Controls collection cannot be modified because the control contains code blocks (i.e. `<%= %>`)."
Now, my question is, "Is there any other way to do the same?"
I am assuming you are using ASP.net not MVC. I have tried this with ASP.net and done this by code behind approach you can create your script tag by code behind like below:
protected void Page_Load(object sender, EventArgs e) {
string jScriptValidator;
jScriptValidator = "<script type='text/javascript' src='../javascript/script.js?v=#123'></script>"; // your dynamic script tag with dynamic parameter
Page.RegisterStartupScript("key", jScriptValidator);
}
and result is follows:
Hope it helps you.
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>
I'm using REST to POST (from Firefox's Poster) a url:
http://[ip]/page.jsp?paramater1=whatever¶meter2=whatever
(Content Type: application/x-www-form-urlencoded)
The page.jsp contains:
<body onload="onload()">
<script>
document.forms["myform"].submit(); // just to be redundant
function onload(){
document.forms["myform"].submit(); // just to be redundant
}
</script>
<form action="SessionTestDriver" method="post" id="myform">
[form stuff]
</form>
But it doesn't seem to be submitting that form. If I manually load the page on a browser, everything works perfectly. It's just the REST call that does nothing.
Clearly I'm missing something. Advice?
SOLVED!
Got it! The main jsp page just called a servlet on submit. I tried that servlet directly in the REST url instead of the jsp page and everything worked how I wanted!
It sounds like you're making a request to a page that contains javascript, and you're concerned that the javascript on the requested page isn't running.
This is expected. When you request that page, the response is returned as a string, and that's it. The page isn't parsed, and javascript isn't evaluated. When you make an AJAX call, don't expect javascript in the page you're POSTing to to run.
(Sorry for explaining something so elementary if I've misunderstood your question.)
Not sure how HTML form and REST are being used, but you might want to make sure the document is loaded entirely first:
Try (if using jQuery)
<script>
$(document).ready( function() {
$("#myform").submit();
});
</script>
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).