in my jsp page I have:
<form:select path="index" id="sIndex" onchange="showDetails()">
<form:options items="${smth}" itemLabel="name" itemValue="index"/>
</form:select>
And in my javascript function:
*function showDetails() {
var sIndex=document.getElementById("sIndex");
var index=sIndex[sIndex.selectedIndex].value;
var name = '${smth[index].name}';
var address = '${smth[index].address}';
var message = "<table><tr><td>Name:</td><td>" + name + "</td></tr>";
message = message + "<tr><td>Address:</td><td>" + address + "</td></tr>"
message = message + "</table>"
document.getElementById("candDetails").innerHTML = message;
}*
And it doesn't takes the index in ${}, but if I use alert(index) it recognize it.
Java/JSP/JSTL runs at the server side, produces HTML/CSS/JS output and sends it to the client. HTML/CSS/JS runs at the client side, not at the server side as you apparently expected. Open the page in your browser and do a 'view source'. Do you see it?
Javascript only sees the HTML DOM tree in the client side and can access it. You need to get the name and address from the HTML DOM tree. You already have the name in the option element, but the address is nowhere available. You could use JSTL to generate a Javascript array variable so that the Javascript code can use it further.
To learn more about the wall between Java/JSP and Javascript you may find this article useful.
The EL expressions (the code between ${}) are evaluated at runtime of the JSP servlet, not once the page has been rendered in the browser, which is when your JavaScript is being called.
View the generated source of the page and you will probably see the problem.
Related
I am beginner in Javascript. I am currentlyworking on a Phonegap app with it. I am stuck in between as I have 4 html pages for signup process, and I have to pass all the html pages input value to single js file as in final all data must be POSTed to server URL and also I have read on many sites that they have recommended using same js file for all the pages of your site to speed up the site. So I have two problems to solve. I searched on many sites but could not find the accurate answer.
I need to pass 4 html page's input value to single js file.
I have to make single js file for both sign-in and sign-up.
My codes for JS page is:
var firstName="";
var lastName="";
var email="";
var password="";
var retypePassword="";
var gender="";
var DOB="";
var institute="";
var course="";
var branch="";
var semester="";
var teachers = [];
function signUpStarting() {
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword+" "+gender+" "+DOB+" "+institute+" "+course+" "+branch+" "+semester+" "+teachers.join(","));
}
function signUp1() {
firstName[0] = $("#first_name").val().trim();
firstName[1] = $("#last_name").val().trim();
email = $("#email").val().trim();
password = $("#password").val();
retypePassword = $("#retype_password").val();
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword);
}
function signUp2() {
gender = $('#gender').find(":selected").text();
DOB = $('#DOB').val();
alert(gender+" "+DOB);
}
function signUp3() {
institute = $('#institute').find(":selected").text();
course = $('#course').find(":selected").text();
branch = $('#branch').find(":selected").text();
semester = $('#semester').find(":selected").text();
alert(institute+" "+course+" "+branch+" "+semester);
}
function signUp4() {
$(":checkbox" ).map(function() {
if($(this).is(':checked')){
teachers.push($('label[for="' + this.id + '"]').text());
}
});
signUpStarting();
}
In html pages I am calling JS functions for each pages:
On first page:
<a onclick="signUp1()" href="register-two.html">continue</a>
On second page:
<a onclick="signUp2()" href="register-three.html">continue</a>
On third page:
<a onclick="signUp3()" href="register-four.html">continue</a>
On fourth page:
<a onclick="signUp4()">continue</a>
On each transaction from one page to next I have set alert in JS, and I am getting alert with accurate values also. But after clicking the continue button from fourth page of html, I transferred the code to main signup function. I tried to see alert in signUpStarting() function but there I am getting response of just fourth page values and other values are showing nothing as the variables are null.
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
Please help me !
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
This is exactly right. You cannot store data in memory between page loads in a web browser environment because all javascript variables are naturally destroyed when the browser navigates away from the page to a new page (even if they use the same javascript on both pages). Thus, you have to save it somewhere with more permanence: localStorage, cookies, or on the server via POST or GET.
What I would recommend is scrapping the four different html pages and simply using one html page that changes dynamically as the user fills in data. This way the browser will not eliminate data before you are ready to POST it to the server.
in my home page i updated the session variable from client side using javascript as per the below:
function test(){
var myvar = "Hi All"
'<% Session("temp") = "' + myvar + '" %>';
alert('<%=Session("temp") %>');
}
the alert shows the updated value which is correct "Hi All", but when trying to catch the session variable in the code behind in other page, i got the name of variable "myvar" not the value of this variable:
MessageBox.Show(HttpContext.Current.Session("temp"), "mymessage")
this message box displays: '+ mayvar +'
any idea about this issue??
thank you in advance
You are mixing client side scripting (javascript) with server side scripting (ASP.NET).
This cannot work.
NOTE: your first code DO NOT UPDATE the session variable with the value of the client-side var "myvar".
Here is the code generated on the client side:
function test() {
var myvar = "Hi All"
'';
alert('' + myvar + '');
}
As you see alert shows the content of the local variable "myvar", and NOT the content of Session.
In order to achieve the result I suggest you to use ajax.
Example:
jquery setting session in asp.net
-> Answer no. 3
It is not possible to assign the session variable on the JavaScript side before sending to server side.
There is a great solution to the problem here: http://www.codeproject.com/Questions/341573/JavaScript-How-to-Set-values-to-Session-in-Javascr
The top voted answer should help you!
I need help. I need to call a Java function "getLocCountByWhId()" in a Java class; this Java function is being called within a JavaScript in a for-loop. I need to pass in a JavaScript variable as a parameter into this Java function "getLocCountByWhId()". I have been struggling for a week and reading numerous website to get some guidelines but I have not been able to resolve the problem. Thank you in advance for your help. The code is listing below:
<script language="JavaScript">
<!--
function onCreatePO()
{
<%long jspAllocId = alloc.getId();%>;
var recItemId = ""; // Local variable for item id.
var recWhId = ""; // Local variable for warehouse id.
for (var i=0, j=document.what_if_summary.elements.length; i<j; i++)
{
var recStr = document.what_if_summary.elements[i].value;
var splitStr = new Array();
splitStr = recStr.split('^');
recItemId = splitStr[1]; // Get the field value for Item_ID.
recWhId = splitStr[2]; // Get the field value for Warehouse_ID.
// Get a database connection with global 'conn' object and retrieve store count.
<%AfsGetVDSCountByWarehouseBean.setConnection(conn);%>;
// The below assignment from JavaScript variable to JSP variable do not work
// because of a second JavaScript tag. How can I get around this ?
//<% String jspItemId = "<script>document.writeln(recItemId)</script>"; %>
//<% String jspWhId = "<script>document.writeln(recWhId)</script>"; %>
currentStoreCount = <%= AfsGetVDSCountByWarehouseBean.getLocCountByWhId(jspAllocId, jspItemId, jspWhId)%>;
}
}
//-->
</script>
// I get this example of assigning Javascript to JSP variable but I got double tag problem.
<script>
var v="Roseindia";
</script>
<% String st="<script>document.writeln(v)</script>";
out.println("value="+st); %>
What you are trying to do is not possible, and (sorry!) reflects a basic misunderstanding as to how server-side code such as JSP (or ASP, PHP, etc) works.
A JSP page is basically a Java servlet running on the web server that dynamically generates a web page and returns it to the browser. The resulting web page may contain HTML, CSS, JavaScript, etc., but to the Java code all of that is just text. The Java/JSP code cannot understand or interact with the JavaScript because the JavaScript doesn't run on the web server, it is just more text to be sent as part of the response back to the browser.
When the browser gets the response it will display the web page and execute any JavaScript.
Further reading (I wouldn't put too much faith in what you read at the RoseIndia site):
http://www.ibm.com/developerworks/java/tutorials/j-introjsp/
http://www.oracle.com/technetwork/articles/javase/servlets-jsp-140445.html
http://java.sun.com/developer/onlineTraining/JSPIntro/
I want to get the title of a webpage without opening it, i.e. without using window.open().
I basically want to check whether the page i am providing the link for exists or an error is returned.
What I am trying is checking for similar links. Here is the code
(I want to know when to break out of this loop, i.e. at what point the link I am writing exists).
document.getElementById("TOI").innerHTML="<p>";
if (month<10) var m="0"+month;
else var m=month;
for(var i=1;;i++){
alert("ji");
var a="http://epaper.timesofindia.com/Repository/CAP/"+year+"/"+m+"/"+date+"/CAP_"+year+"_"+month+"_"+date+"_"+i+".pdf";
alert(a);
var link=window.open(a);
window.focus();
alert(link.location);
alert(link.document.title);
if(link.document.title!="The page cannot be found"){
link.close();
document.getElementById("TOI").innerHTML=document.getElementById("TOI").innerHTML+"<a href='http://epaper.timesofindia.com/Repository/CAP/"+year+"/"+m+"/"+date+"/CAP_"+year+"_"+month+"_"+date+"_"+i+".pdf' target=_blank>Page "+i+"</a> ";
}
else{link.close();break;}
}
document.getElementById("TOI").innerHTML=document.getElementById("TOI").innerHTML+"<\p>";
}
See to check if a url exists or not, you must use a server-side scripting language. Javascript is client-side and can't access server. So, first of all make a server side script (maybe php) that returns the status of url that you wanna check. Then from javascript side, use an ajax call to get the result of that script. That way you can check your url array, if all of them exists or not.
var attribute = element.getAttribute("title");
I want to get title of a webpage
without opening it(that is without
using window.open()) I basically want
to check whether the page i am
providing the link for exists or an
error is returned
Just because a page has a title doesn't mean it exists.
http://www.google.com/thispagedoesnotexist.htm
Examine HTTP status codes rather than page titles:
Can Prototype or JQuery return an HTTP status code on an AJAX request
I have a fly out javascript menu that is initialized using the onload event. All of the data inside the menu right now is hard coded but needs to be dynamic and will come from my database. Is there a way to build this javascript file with my database values? Is this possible? I'm a total noob to JS so please spell things out for me.
Maybe an example of what I'm thinking will help. This is part of my JQuery file after I have my serialized array. How do I get the array into the menu from here?
if(data.success == 0) {
// error
} else {
// my array that needs to be exported into the JS file.
}
This is the other file that I'm talking about that needs to be built with the data from the database.
function create_menu()
{
document.write(
'<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' +
'<td class="td" valign="top">' +
'<h3>Test</h3>' +
'<ul>' +
'<li>afd</li>' +
'<li>fsg</li>' +
'<li>sfg</li>' +
'<li>fsg</li>' +
'</ul>' +
'</td></tr></table>');
}
One option would be to build the JavaScript file dynamically on the server when a request comes in from the browser using one of the various server-side scripting languages. The downside to this method is that that browsers may cache the file and, therefore, may operate with stale data.
The other option is to use a static JavaScript file and use an AJAX call to get the latest menu options and then render them into the page's DOM. This would be better than the first option since you wouldn't have the caching concerns.
The third method is to dynamically generate the markup for the page and not worry about requesting a menu via JavaScript. This is the best option in my book. I wouldn't want to wait for the navigational elements of a page to be requested via JavaScript when it's something simple that should already be part of the page.
You need to use AJAX.
You can load the contents from back-end into a JavaScript array and use that. This is how dynamic data is fetched from the server without a page refresh.
Hope this helps.
JSON is a data format which can be executed using eval(). Create some JSON which represents whatever format you've hard-coded and evaluate it like in Wikipedia's example
This is only okay if you trust the source of the JSON, in this case you're generating it yourself so it should be okay.
example, json_menu.php returns the text:
create_menu( { "menus" : ["afd", "fsg", "sfg", "fsg"] } );
And you execute it like this by evaluating it:
function create_menu(JSONData)
{
var s = '<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' +
'<td class="td" valign="top">'
// loop through each one
for(var menu in JSONData.menus)
s = s + '<li>' + menu + '</li>';
s = s + '</ul></td></tr></table>';
// write it out
document.write(s);
}
// this gets called somewhere in your OnLoad
function yourOnLoader()
{
var ajaxRequest = new ajaxObject('http://your-site.com/json_menu.php');
ajaxRequest.callback = function (responseText) { eval(responseText); }
ajaxRequest.update();
}