How can i access javascript variables in JSP? - javascript

I want to access Javascript variables in JSP code. How can I do that?

JavaScript variable is on client side, JSP variables is on server side, so you can't access javascript variables in JSP. But you can store needed data in hidden fields, set its value in client and get it on server over GET or POST.
Client side:
<script type="text/javascript">
var el = document.getElementById("data");
el.value = "Needed_value";
</script>
<form action="./Your_JSP.jsp" method="POST">
<input id="data" type="hidden" value="" />
<input type="submit" />
</form>
server side:
<%
if (request.getParameter("data") != null) { %>
Your value: <%=request.getParameter("data")%>
<%
}
%>

I came across the same issue. I wanted to fetch couple of data in jsp. What I did is, in javascript function I concatenated the data in one variable with delimiter and passed that variable in parameter like this.
function myname()
{
var fname = "FirstName";
var lname = "LastName";
var fullname = fname+","+lname;
document.location.href = "demopage.jsp?name="+fullname;
}
And then in jsp page, we can fetch the full name as,
<c:set var="varname" value='<%= request.getParameter("name") %>' />
Now we can split the first name and last name using delimiter ','.

function call()
{
var name="xyz";
window.location.replace=("a.jsp?m="+name);
}
String name=request.getParameter("name");
if(name!=null){
out.println(name);
}

Related

i am trying to get value from javascript to jsp using hidden field but how to know that i am getting the value on the same jsp page

<html>
<script>
function brnch()
{
var client_code = document.getElementById("cname").value;
xmlobj=ajaxFunction();
xmlobj.onreadystatechange=function(){
if(xmlobj.readyState == 4)
{
var resp = xmlobj.responseText;
document.getElementById("brch").value=resp;
}
}
var url="getbranch.jsp?c_code="+client_code;
xmlobj.open("POST",url,true);
xmlobj.send();
}
</script>
<input type="hidden" name="brancht" id="brch" value="">
<%
String value=request.getParameter("brch");
System.out.println("hidden field :"+value);
%>
</html>
i am trying to get value from javascript to jsp using hidden field but how
to know that i am getting the value on the same jsp page.
To check you got parameter value or not, you can compare with null value as below.
if(Request.getParameter("brch")!=null)
{
...
...
}

Passing HTML parameters to php page

I am attempting to pass the parameters of the current html page to the php page using a form. So far I have the following function inside my header in the html
<script>
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
</script>
and then in the form I have the following
<input type="hidden" name="amtpaid" id="amtpaid" value="getURLParameter('amt')" />
<input type="hidden" name="status" id="sts" value="getURLParameter('st')" />
this is assuming a url such like
www.somehost.com/page/?amt=5&sts=CONFIRMED
however all that the php says is posted is the following (this is aa dump of all post data)
Array ( [on1] => Steam 32 - ID (STEAM_0:X:XXXX) [os1] => hj [amtpaid] => getURLParameter('amt'); [status] => getURLParameter('st'); )
anyhelp??
You're passing the literal string "getUrlParameter('amt')" as the value of the fields you are posting. You can't populate the "value" in this way. What you need to do is populate the values from javascript. Like this:
document.getElementById("amtpaid").value = getUrlParameter('amt');
document.getElementById("sts").value = getUrlParameter('st');
This would need to be placed somewhere in a script tag in the page where it would be executed at a time that makes sense for your application, after those two hidden fields are loaded.
Put this script under your form or input fields:
var amount = getURLParameter('amt');
var stat = getURLParameter('sts');
document.getElementById("amtpaid").value = amount;
document.getElementById("sts").value = stat;

Using onclick event to submit 2 parameters into a the same servlet

I'm trying to use a submit button to pass 2 parameters, userId and friendId, using jsp into the same servlet. I am able to obtain friendId, however, I am not able to obtain the userId.
function anotherPageServlet(servletName) {
document.forms[0].method = "post";
document.forms[0].action = servletName;
document.forms[0].submit();
}
function anotherPageServlet1(servletName) {
document.forms[0].method = "post";
document.forms[0].action = servletName;
document.forms[0].submit();
}
<input style="color:#3333ff"
type="submit"
class="rsubmit"
value="<%= retrieving.getDisplayname()%> :"
onclick="anotherPageServlet('ViewingFriendServlet?stringParameter=<%= session.getAttribute("userId") %>'),
anotherPageServlet1('ViewingFriendServlet?stringParameter=<%=retrieving.getoID() %>')"
>
You probably only need to escape the quotes:
onclick="anotherPageServlet('ViewingFriendServlet?stringParameter=<%= session.getAttribute(\"userId\") %>'),
anotherPageServlet1('ViewingFriendServlet?stringParameter=<%=retrieving.getoID() %>')"
I'm not used to JSP, but in JSF you would rather assign values to a request-scoped bean and then call a function that works with that bean, rather than passing those arguments directly.
EDIT:
Define onclick functions first, then call only the simple reference.
function servletFoo() {
anotherPageServlet('ViewingFriendServlet?stringParameter=<%= session.getAttribute("userId") %>');
anotherPageServlet1('ViewingFriendServlet?stringParameter=<%=retrieving.getoID() %>');
}
Then in your HTML:
<input ... onclick="servletFoo()" />

How to read <input type="hidden"...> in JavaScript on subsequent page?

One first page:
A form SUBMIT goes to a subsequent page.
VBscript can see the hidden value with ... Request("myName") ...
How do I do the same thing in JavaScript.
alert(window.location.search);
or
alert(window.top.location.search.substring(1));
return nothing.
Well, you dont. When you submit a form it sends the values to a server, and the "server-side" reads that in vbscript as Request (Requested). If you want to let the requested value accessible to the Javascript, your server-side (subsequent) page must write that Request data back to the client-side, in other worlds, you have to write the requested value directily in the HTML that will be send back to the client browser.
Ex: In your ASP (Server-Side Subsequent VBScript file) you should write
Response.Write ("<script type=""text/javascript"">alert('" & Request("Data") & "')</script>")
<input type='hidden' id='hiddenId'/>
jQuery:
var value = $('#hiddenId').val();
alert(value);
Or
var value = document.getElementById('hiddenId').value;
alert(value);
In your form, you have to have the method set to GET.
<form method="GET" action="somepage">
<input type=hidden name=myHiddenValue />
</form>
Then on the next page, you can parse the search part of the url with a function like this.
function parseSearch(search, key) {
search = search.substring(1), items=search.split("&");
for (var i=0; i<items.length; i++) {
var item = items[i], parts = item.split("=");
if (parts[0] === key) {
return parts[1] || true;
}
}
}
parseSearch(location.search, "myHiddenValue"); // returns the hidden value
live demo

javascript : sending custom parameters with window.open() but its not working

<html>
<head>
<script>
function open_win()
{
window.open("http://localhost:8080/login","mywindow")
}
</script>
</head>
<body>
<input type="button" value="Open Window" onclick="open_win()">
</body>
</html>
Hi ,
On click of a button , i am opening a new website (My web site )
I have two text fields ( One Text Field and another Password Field) , i am trying to send this values to the other opened window .
But its not working as I want.
I have tried the following ways
1. window.open("http://localhost:8080/login?cid='username'&pwd='password'","mywindow")
2. window.open("http://localhost:8080/login","mywindow")
mywindow.getElementById('cid').value='MyUsername'
mywindow.getElementById('pwd').value='mypassword'
Could anybody please help me if this is possible or not ??
Sorry for the incomplete details , its a Post request .
if you want to pass POST variables, you have to use a HTML Form:
<form action="http://localhost:8080/login" method="POST" target="_blank">
<input type="text" name="cid" />
<input type="password" name="pwd" />
<input type="submit" value="open" />
</form>
or:
if you want to pass GET variables in an URL, write them without single-quotes:
http://yourdomain.com/login?cid=username&pwd=password
here's how to create the string above with javascrpt variables:
myu = document.getElementById('cid').value;
myp = document.getElementById('pwd').value;
window.open("http://localhost:8080/login?cid="+ myu +"&pwd="+ myp ,"MyTargetWindowName");
in the document with that url, you have to read the GET parameters. if it's in php, use:
$_GET['username']
be aware: to transmit passwords that way is a big security leak!
Please find this example code, You could use hidden form with POST to send data to that your URL like below:
function open_win()
{
var ChatWindow_Height = 650;
var ChatWindow_Width = 570;
window.open("Live Chat", "chat", "height=" + ChatWindow_Height + ", width = " + ChatWindow_Width);
//Hidden Form
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "http://localhost:8080/login");
form.setAttribute("target", "chat");
//Hidden Field
var hiddenField1 = document.createElement("input");
var hiddenField2 = document.createElement("input");
//Login ID
hiddenField1.setAttribute("type", "hidden");
hiddenField1.setAttribute("id", "login");
hiddenField1.setAttribute("name", "login");
hiddenField1.setAttribute("value", "PreethiJain005");
//Password
hiddenField2.setAttribute("type", "hidden");
hiddenField2.setAttribute("id", "pass");
hiddenField2.setAttribute("name", "pass");
hiddenField2.setAttribute("value", "Pass#word$");
form.appendChild(hiddenField1);
form.appendChild(hiddenField2);
document.body.appendChild(form);
form.submit();
}
To concatenate strings, use the + operator.
To insert data into a URI, encode it for URIs.
Bad:
var url = "http://localhost:8080/login?cid='username'&pwd='password'"
Good:
var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;
The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.
… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).
You can use this but there remains a security issue
<script type="text/javascript">
function fnc1()
{
var a=window.location.href;
username="p";
password=1234;
window.open(a+'?username='+username+'&password='+password,"");
}
</script>
<input type="button" onclick="fnc1()" />
<input type="text" id="atext" />
You can try this instead
var myu = document.getElementById('myu').value;
var myp = document.getElementById('myp').value;
window.opener.location.href='myurl.php?myu='+ myu +'&myp='+ myp;
Note: Do not use this method to pass sensitive information like username, password.
I found this method very useful, I hope this will be helpful for many users too.
// --> screen 1:
var url = 'screen_2_url';
var id = 'some_ID';
window.open(url + '?id=' + id);
This will open the Screen 2 tab. There you can get the passed values like this:
// --> screen 2:
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const id = urlParams.get('id');
I agree that passing username and password as parameters is a bad idea, no matter how you do it.
However, if it's same site, you could use sessionStorage, like so:
sessionStorage.setItem('username', username)
sessionStorage.setItem('password', password)
window.open("http://localhost:8080/login","mywindow")
And then in the opened window:
var username = sessionStorage.getItem('username')
var password = sessionStorage.getItem('password')
// if you no longer need them:
sessionStorage.removeItem('username')
sessionStorage.removeItem('password')

Categories

Resources