How to read the value of variable in JS in the scope of JSP on the same page? - javascript

I have a JSP page in which third party sign-in plugin is used, which is JS. After sign-in is successful, the user-id obtained in JS has to be used in JSP to maintain session by storing that value.
For this, I tried 'manipulating' jQuery but that works only if the JS value is a literal or is pre-known. But here in this case, value is fetched at runtime as per sign in.
Also tried <% String s = "<script>document.writeln(var)</script>"; %>
But again the above problem. works only when value is known before hand.
document.getElementById("ppurl").innerHTML = ppurl; prints the value. But I want to store it.
So, how to achieve the purpose of passing a variable's value in JS to JSP?

Assuming your third party sign-in plugin is client-side JavaScript:
Remember that the JavaScript runs when the page reaches the client. The JSP code has long since completed and so is no longer in the picture.
You have three options that I can immediately see:
Send the data to the server using Ajax or similar.
Refresh the page (sending the login data to the server as part of the refresh).
Update whatever it is on the page that you want to have this value in it via the DOM.
#1 and #2 should be fairly self-explanatory.
For #3: Say you have various forms on the page and you want to make sure that the login token or whatever it is you get from the client-side plugin gets sent with the form using a hidden field in the form with the name tokenField. You could do this:
function putTokenOnForms(token) {
var forms, index, form;
forms = document.getElementsByTagName("form");
for (index = 0; index < forms.length; ++index) {
form = forms[index];
if (form.tokenField) {
form.tokenField.value = token;
}
}
}
You can do much the same with links in a elements (adding to the href property of each link that goes back to your server), etc.

The page outputting the JavaScript to the client cannot read data back from that JavaScript.
You need to initiate a new HTTP request (e.g. using XMLHttpRequest or setting location.href) that passes the data back to the server and then read it in (e.g. from the query string or POST data).

Store it in a cookie using JS. Read it back in JSP.
In your JS, after you get the userID, you can do:
document.cookie = 'myuserid='+userID;
In your JSP, you can read it back like:
Cookie[] cookies = request.getCookies();
String userID;
for(int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
if (c.getName().equals("myuserid")) {
userID = c.getValue(); // c.getValue() will return the userID
break;
}
}

Related

Passing section of query result into session variables with Javascript

I'm having trouble passing the result of a query into a session variable, I think that the easiest way to do this is through Javascript. I have the query result showing but they will not pass to the session variable. At the end of each query resultant row, I have an add button that will activate the JS function to add to the session variable.
Query Result:
echo '<tr><td>'.$products['Name'].'</td><td>£'.$products['Price'].'</td><td>'.$products['Category'].'</td><td><img src="'.$products['Image'].'" width=100px /></td><td>'.$products['ProductID'].'</td><td><button onclick="setProduct('.$products['ProductID'].')">Add to Basket</button></td></tr>';
JS Function:
function setProduct(x){
var productID = x;
'<%Session["ProductID"] = "'+$products['productID']+'";%>';
Code displaying contents of session variable:
echo $_SESSION['ProductID'];
$_SESSION is a server-side variable. You'd most likely want to set a $_COOKIE instead. Those are accessible on the client-side.
In addition to the answer posted, you can create a jQuery post request (or you can use AJAX) and send the JS session as value to a PHP file where you can access that value and create the corresponding PHP session.
Let's say, your JS function:
function setProduct(x){
var productID = x;
'<%Session["ProductID"] = "'+$products['productID']+'";%>';
// ...
$.post('example.php', { session_name: YOUR-SESSION-NAME, session_value: YOUR-SESSION-VALUE });
example.php:
if (isset($_POST['session_name']) && isset($_POST['session_value'])) {
$_SESSION[$_POST['session_name']] = $_POST['session_value'];
}
This is not taking into consideration security issues you might face. You should encrypt your data before sending it.

Javascript file for multiple html pages

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.

Could this cause a rails to detect a CSRF?

Ok, so in my rails app on one of the pages I needed to pass a Javascript variable so that it was available to rails. Now one runs server side and one runs client side so I know this is very difficult. I looked to the internet and found a solution that involved dynamically creating a form in a function included in my external javascript page.
Basically, a form with a hidden field was made using document.createElement statements and the hidden field was given the value of what I wanted to pass to rails and then form.submit() is called so that the form is submitted. the form was given a method of post and it was given a path to go to. So when submit it called the page redirects to another page with the hidden field now in the params hash and accessible by rails with params[:param].
This worked great for a while, until we started using session to keep track of a logged in user. After clicking the button to be redirected with that dynamic form the session gets cleared. The only thing I found online about sessions being cleared is when rails detects a CSRF it clears the session.
So could what I'm doing cause rails to detect a CSRF and thus clear my session? is there any other reason the session might be cleared that anybody knows of? Also, without ajax (because I'm just not up to screwing with that, it doesnt play nicely.) is there another good way im missing to pass a javascript variable (it has to be javascript, I'm using a javascript function to get the users current location) so that it is available to rails? (I'm thinking rather than javascripting the form, I might just make a hidden form right on my page, although this is a little less elegant because anybody looking at the source can see it and wonder why its there and screw with it)
if anybody is interested, below is the code for my dynamic form function.
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path); //page to go redirect to when form submitted
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
//after form is submitted params is available by params[:location]
hiddenField.setAttribute("name", 'location');
hiddenField.setAttribute("value", params )
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
}
In any form requests, and ajax the CSRF token must be passed through. You need to create a hidden field in the form with the name authenticity_token. Then you need to grab the value from the meta tag:
<meta content="some_token_value" name="csrf-token" />
Like so:
var token = "";
var tags = document.getElementsByTagName("meta");
for(var i = 0; i < tags.length; i++) {
if(tags[i].name == "csrf-param") {
token = tags[i].content;
}
}
Then simply drop that in the value of the hidden tag, much like you did for the location value.
you can add an erb line in your javascript file:
var csrf_token = '<%= form_authenticity_token %>';
then in your requests, add 'authenticity_token' : csrf_token in the post-data.

Calling a Java function with a JavaScript variable inside a JavaScript function

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/

Make an ajax request to get some data, then redirect to a new page, passing the returned data

I want to redirect after a successful ajax request (which I know how to do) but I want to pass along the returned data which will be used to load an iframe on the page I just redirected to.
What's the best way to pass such data along and use it to open and populate an iframe in the page I just redirected to?
EDIT:
I am passing a GET variable but am having to use the following to access it for use in my iframe src attribute:
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
var d = $_GET('thedata');
I assume there isn't really a more straightforward way to access the GET vars?
If it's not too much data, you could pass it as a get parameter in the redirect:
document.location = "/otherpage?somevar=" + urlescape(var)
Remember that urls are limited to 1024 chars, and that special chars must be escaped.
If it is beyond that limit your best move is to use server side sessions. You will use a database on the server to store the necessary information and pass a unique identifier in the url, or as a cookie on the users computer. When the new page loads, it can then pull the information out of the database using the identifier. Sessions are supported in virtually every web framework out of the box.
Another alternative may be to place the data as a hidden attribute in a form which uses the post method (to get around the 1024 char limit), and simulating a submission of the form in javascript to accomplish the redirect, including the data.

Categories