How to get session data in .js file - javascript

In my application when the user is login the particular user id is stored in the session. I want to get this id in a js file.In this js file contain state provider,factory etc
js
var sessionValue = "'"+<%=Session["userId"]%>+"'"
alert(sessionValue)
But it is show some error(Unexpected)

1.You can assign session value to hidden field.
<input type="hidden" name="userId" id="userId" value="<%= Session["userId"] %>">
Get hidden field value from javascript function.
function GetUserId()
{
var userId = document.getElementById('userId').value;
alert(userId);
}

You can use something like
<script type="text/javascript">
function GetUserId()
{
var userId = '<%= Session["userId"] %>';
alert(userId);
}
</script>

I think that the problem is that your webserver isn't evaluating as ASP .js files. You have three different way to get what you want
configure your webserver so that .js files are treated as ASP pages,
but noone would ever do that, it would add overhead over your
code.
Render your js starting from a .asp page placing in your html
something like: < script src="mysite/getjavascript.asp" >
Load session values with an ajax calls
Remember to print proper headers before printing your javascript

Related

Passing Array to Script in EJS file [duplicate]

I'm working on a Node.js app (it's a game). In this case, I have some code set up such that when a person visits the index and chooses a room, he gets redirected to the proper room.
Right now, it's being done like this with Express v2.5.8:
server.get("/room/:name/:roomId, function (req, res) {
game = ~databaseLookup~
res.render("board", { gameState : game.gameState });
}
Over in board.ejs I can access the gameState manner with code like this:
<% if (gameState) { %>
<h2>I have a game state!</h2>
<% } %>
Is there a way for me to import this into my JavaScript logic? I want to be able to do something like var gs = ~import ejs gameState~ and then be able to do whatever I want with it--access its variables, print it out to console for verification. Eventually, what I want to do with this gameState is to display the board properly, and to do that I'll need to do things like access the positions of the pieces and then display them properly on the screen.
Thanks!
You could directly inject the gameState variable into javascript on the page.
<% if (gameState) { %>
<h2>I have a game state!</h2>
<script>
var clientGameState = <%= gameState %>
</script>
<% } %>
Another option might be to make an AJAX call back to the server once the page has already loaded, return the gameState JSON, and set clientGameState to the JSON response.
You may also be interested in this: How can I share code between Node.js and the browser?
I had the same problem. I needed to use the data not for just rendering the page, but in my js script. Because the page is just string when rendered, you have to turn the data in a string, then parse it again in js. In my case my data was a JSON array, so:
<script>
var test = '<%- JSON.stringify(sampleJsonData) %>'; // test is now a valid js object
</script>
Single quotes are there to not be mixed with double-quotes of stringify. Also from ejs docs:
"<%- Outputs the unescaped value into the template"
The same can be done for arrays. Just concat the array then split again.
I feel that the below logic is better and it worked for me.
Assume the variable passed to the ejs page is uid, you can have the contents of the div tag or a h tag with the variable passed. You can access the contents of the div or h tag in the script and assign it to a variable.
code sample below : (in ejs)
<script type="text/javascript">
$(document).ready(function() {
var x = $("#uid").html();
alert(x); // now JS variable 'x' has the uid that's passed from the node backend.
});
</script>
<h2 style="display:none;" id="uid"><%=uid %></h2>
In the EJS template:
ex:- testing.ejs
<html>
<!-- content -->
<script>
// stringify the data passed from router to ejs (within the EJS template only)
var parsed_data = <%- JSON.stringify(data) %>
</script>
</html>
In the Server side script:
ex: Router.js
res.render('/testing', {
data: data // any data to be passed to ejs template
});
In the linked js (or jquery) script file:
ex:- script.js
In JavaScript:
console.log(parsed_data)
In JQuery:
$(document).ready(function(){
console.log(parsed_data)
});
Note:
1. user - instead of = in <% %> tag
2. you can't declare or use data passed from router to view directly into the linked javascript or jquery script file directly.
3. declare the <% %> in the EJS template only and use it any linked script file.
I'm not sure but I've found it to be the best practice to use passed data from router to view in a script file or script tag.
This works for me.
// bar chart data
var label = '<%- JSON.stringify(bowlers) %>';
var dataset = '<%- JSON.stringify(data) %>';
var barData = {
labels: JSON.parse(label),
datasets: JSON.parse(dataset)
}
You can assign backend js to front end ejs by making the backend js as a string.
<script>
var testVar = '<%= backEnd_Var%>';
</script>
This should work
res.render("board", { gameState : game.gameState });
in frontend js
const gameState = '<%- JSON.stringify(gameState) %>'
Well, in this case you can simply use input text to get data. It is easy and tested when you use it in firebase.
<input type="text" id="getID" style="display: none" value="<%=id%>">
I know this was answered a long time ago but thought I would add to it since I ran into a similar issue that required a different solution.
Essentially I was trying to access an EJS variable that was an array of JSON objects through javascript logic like so:
<script>
// obj is the ejs variable that contains JSON objects from the backend
var data = '<%= obj %>';
</script>
When I would then try and use forEach() on data I would get errors, which was because '<%= obj %>' provides a string, not an object.
To solve this:
<script>
var data = <%- obj %>;
</script>
After removing the string wrapping and changing to <%- (so as to not escape html going to the buffer) I could access the object and loop through it using forEach()
Suppose you are sending user data from the node server.
app.get("/home",isLoggedIn,(req,res)=>{
res.locals.pageTitle="Home"
res.locals.user=req.user
res.render("home.ejs");
})
And now you can use the 'user' variable in the ejs template. But to use the same value using client-side javascipt. You will have to pass the data to a variable in the tag.
Passing ejs variable to client-side variable:
<script>
let user= '<%- JSON.stringify(user) %>';
</script>
<script>home.js</script>
Now you can access the user variable at home.js

Displaying data on next page with jQuery session or another possible way?

here my simple form:
<form id="myform">
Name:<input type="text" name="name"><br>
Email:<input type="text" name="email">
<a class="btn btn-primary" id="click_btn">Submit</a>
</form>
I want to submit the form with Ajax, that bit is okay so far, and submitting.
Here is my jquery code:
$(document).ready(function() {
$('#click_btn').on('click', function() {
$.ajax({
url: $('myform').attr('action'),
data: $('myform').serialize(),
method: 'post',
success: function(data) {
//success meseg then redirct
alert('success');
var data = $('#myform').serializeArray();
var dataObj = {};
$(data).each(function(i, field) {
dataObj[field.name] = field.value;
window.location.href = 'next_page.php';
});
}
})
});
})
next_page.php is where I want to access, example:
<?php echo document.write(dataObj["email"]); ?>
I want to access these form values that I have submitted on next page after the form is submitted. I have created a data object with all the values using jQuery after submit, but still, I cannot access on the next page. Is there any concept related to the session in jquery for storing that array.
I think you're getting a couple of concepts confused here; I don't mean that in a condescending way, just trying to be helpful.
jQuery, and all JavaScript, exists only on the client-side (for practical purposes - there are exceptions where some client-side code might be rendered or compiled on the server-side for whatever reason but that's another matter). PHP, like any other server-side language, exists on the server-side. These two can't directly access each other's scope - which is why AJAX is useful to transfer data between the front and back ends.
Basically what you appear to be doing here is loading the data in the client-side, but not submitting anything to the server-side. You aren't actually doing any AJAX queries. When you redirect the user via window.location.href =..., no data is actually being transmitted - it simply instructs the browser to issue a new GET request to next_page.php (or wherever you instruct it to go).
There are a couple of options to do what you're trying to achieve:
Actually submit an AJAX query, using the methods outlined here http://api.jquery.com/jquery.ajax/. You can then use next_page.php to grab the data and store it in a session and recall it when the user arrives on the page.
Store the data in a client-side cookie.
Use the standard HTML <form method="next_page.php"...><input type="submit"> to cause the browser to forward the form data to the next_page.php script.
A number of other options but I think those are the simplest.
You can totally use sessionStorage ! (Here is documentation)
If user direct to next page in same tab, sessionStorage can easily save you data and reuse in next page.
// set in page A
window.sessionStorage.setItem('youdata', 'youdata');
// or window.sessionStorage['youdata'] = 'youdata';
// get in page B
var youdata = window.sessionStorage.getItem('youdata');
// or var youdata = window.sessionStorage['youdata'];
That's it! very simple!
If you'll open a new tab, you can use localStorage. (Here is documentation)
The usage of localStorage is like the way of sessionStorage.
While do saving information for other pages, these two method only need browsers' support.
<?php echo document.write(dataObj["email"]); ?>
This is unreasoned! echo is a PHP command, but document.write is a JavaScript command.
If the secound page is PHP, why not send data with a simple POST submit from HTML Form?
You can also use localStorage:
var data = '123';
localStorage['stuff'] = data;
Use localStorage.clear(); to remove all data if you want to write it again or for specific item use localStorage.removeItem('stuff');
List of some possible solutions are as follows:
1. Post the data using AJAX request and the get it in next page by doing DB call (Advisable)
2. Using Local storage you can store the data in the browser to push it to next_page.php https://www.w3schools.com/Html/html5_webstorage.asp
2a. In the first page
<script>
localStorage.setItem("name", "John");
localStorage.setItem("email", "John#test.com");
</script>
2b. In second Page
<script>
var name = localStorage.getItem("name");
var emaeil = localStorage.getItem("email");
</script>
3. Using browser session storage https://www.w3schools.com/jsref/prop_win_sessionstorage.asp
3a. In the first page
<script>
sessionStorage.setItem("name", "John");
sessionStorage.setItem("email", "John#test.com");
</script>
3b. In second Page
<script>
var name = sessionStorage.getItem("name");
var emaeil = sessionStorage.getItem("email");
</script>

How you can save appends to variables an then convert them to php so you can save them in a database?

<html>
<head>
<meta charset="utf-8">
<title>Test page for Query YQL</title>
<link rel="stylesheet" href="http://hail2u.github.io/css/natural.css">
<!--[if lt IE 9]><script src="http://hail2u.github.io/js/html5shiv.min.js"></script><![endif]-->
</head>
<body>
<h1>Test page for Query YQL</h1>
<div id="content"></div>
<input type="button" name="bt1" value="click" onclick="pesquisa()">
<form name="s2">
<input type="text" name="s1">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jquery.query-yql.min.js"></script>
<script type="text/javascript">
function pesquisa(){
$(function () {
var t = $('#content').empty();
var url= document.s2.s1.value;
var statement = 'select * from feed where url="'+url+'"';
$.queryYQL(statement, function (data) {
$('<h2/>').text('Test: select * from feed').appendTo(t);
var r = data.query.results;
var ul = $('<ul/>');
$.each(r.item, function () {
$('<li/>').append(this.title).appendTo(ul);
$('<li/>').append(this.link).appendTo(ul);
<?php
$titulo = "<script>document.write(titulo);</script>";
$site = "<script>document.write(site);</script>";
//echo $titulo;
//echo $site;
?>
});
ul.appendTo(t);
});
});
};
</script>
</body>
</html>
How can you save the this.title and the this.link values into 2 different variables an then call them into php so you can insert the data into a DB?
It's just a simple YQL query to search on rss feeds.
After doing the query, I want the results to be saved in a database, but I can't discover how to do that.
First of all, you have to understand that you are working on a Client-Server architecture.
This means:
Let's say that this file you are showing us is called "TestYQL.php" (because you did not say the name of it). This file is executed by php (server side), which reads line by line the contents of it, and generates another new file from the original. For educational purposes, let's say the generated file is called "GeneratedTestYQL.html". This file no longer has any php code inside, since it is directly html and js flat. It knows nothing about php. So there are no php functions, variables, nothing. This last file is the one that reaches the client, and the code is executed by a web browser like Chrome, Firefox, etc.
In your case, the file "TestYQL.php" all you have of php is what is inside the <? Php ....?> Tags. With php you creates 2 variables, each with a tag inside, but without any purpose since they are not used in any way. So, the generated "GeneratedTestYQL.html" file is the same as the original, but without the lines inside the <? Php ...?>.
This means that: The contents of the variables that you use in PHP can be sent to the browser, because with PHP you will generate the file that will be executed in the browser.
Now, when the file "GeneratedTestYQL.html" arrives, the browser starts to show all the contents of the file, it generates the form in which, when you click the button, executes the function pesquisa() and now starts javascript (JQuery) bringing data of the feeds, and for the first time, these variables "this.title" and "this.link" begin to exist in javascript.
Since there is no such thing as php here, you can NOT access those variables from php.
So, how to save that data in a DB?, well, the common way is to send all the data you want from the browser, to the server, then the server sees what to do with that data. To send data from the browser to the server, you do it by making GET or POST requests to a php file from the server (preferably another file, let's say it will be called "saveFeeds.php").
Data can be sent with a GET request, but it is semantically incorrect since GET means you want to fetch data from the server. So to send that data to the server, you will have to make a POST request from the browser, which is more appropriate.
There are now 2 simple ways to make a POST request. The first and most common of these is from a form in the browser, the other way is using Ajax.
How to do it from a form?
Currently in your code, you have already put a form (That is called "s2"), although currently the same is not necessary, but leave that now.
If you wanted to send the data through a form, you should do 2 things. First and most obvious, create the form; second, the data received from the internet (title and link of feed), send them to the server.
Assuming you fetch data from a single feed per url, and the designated file in charge of receiving the request will be "saveFeeds.php". So, you could create a form like the following after the previous one:
<Form class = "sender" action = "saveFeeds.php" method = "post">
  <Input type = "hidden" name = "title" value = ""> <br>
  <Input type = "hidden" name = "link" value = ""> <br>
  <Input type = "submit">
</ Form>
Then you need to put the feed data inside the form, because, at this moment, you can't send anything. You could add a function like:
Function appendFeedToForm (title, link) {
  Var form = $ (". Sender");
  Form.title.value = title;
  Form.link.value = value;
}
And then call it from inside the $ .each of the result as
AppendFeedToForm(this.title, this.link);
The second case, the easiest way to make a request to the same file using Ajax is with a JQuery shortcut:
$.post("saveFeeds.php", r.item);
If you are interested in validations, you can take a look at the JQuery documentation. The important thing about ajax requests is that you can send all the data you want without having to force you to reload the page. Therefore, you can send as many feeds as you want in the same way you would send one.
Now with the data sent from the client to the server, it is necessary to handle the reception of the data. Currently we were pointing all the data to the file "saveFeeds.php", so, now, finally we can put the content from javascript. To access them, simply in that file, you should check the fields:
$ _POST ['title'] // This names are from input names of form
$ _POST ['link'] // or properties sended through Ajax
So, here, you have tp prepare the connection to your database and save those parameters. Currently you did not mention which database engine you are using, so, for this moment, I'll shorten the answer here.
Note: I was not giving you the best practices to solve your problem, but rather the minimum necessary.

Unable to retrieve value set in servlet

I have, what I believe, is an extremely simple problem, yet all of my attempts to resolve it have failed.
In a nutshell:
I have a JSP file with a form that invokes a Java Servlet.
The servlet processes the input and returns a variable (attribute) and redirects back to the same jsp.
I want to the jsp to process the returned attribute using JavaScript, NOT a scriptlet.
JSP Code (test.jsp):
<html>
...
<%#page language="java"
import="java.sql.*"
import="java.util.*"
%>
...
<body>
<script type='text/javascript'>
var name = session.getAttribute("test");
alert(name);
</script>
...
</body>
</html>
And the Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
request.getSession().setAttribute("test", "value");
String redirectedPage = "/test.jsp";
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher(redirectedPage);
reqDispatcher.forward(request,response);
}
I believe that the problem stems from my declaration of the session variable:
var name = session.getAttribute("test");
I have also tried:
var name = (String) session.getAttribute("bob");
and:
String name = (String) session.getAttribute("bob");
I can access this attribute from within my form using a scriptlet (<% %>), but that doesn't allow me to modify/process the returned attribute, which I need to do.
Any help is greatly appreciated. If you feel this question has already been asked/addressed (I've searched), please POLITELY let me know.
You can not access the session from javascript, but you can of course create your javascript on the server side.
<script type='text/javascript'>
var name = '<%= session.getAttribute("test") %>';
alert(name);
</script>
If you don't have 100% control of the actual value (and maybe even then) it's is a good idea to escape the string. Otherwise someone might inject values that breaks your page (best case) or enables some XSS to steal user data or hijack user session.
Using Apache commons StringEscapeUtils (JavaDoc) It would look like this
<script type='text/javascript'>
var name = '<%= StringEscapeUtils.EscapeJavaScript((String)session.getAttribute("test")) %>';
alert(name);
</script>
If you are going to use this a lot (or maybe just even once) I'd recommend creating a tag that takes the attribute name and outputs a javascript safe string. Maybe as <MyJsTags:AttributeAsString name="test"/> to avoid script lets in your JSP and it also makes it easier if you want to impose new functionality when accessing the attribute.

passing value from one page to another with javascript

How can I pass the value of textarea to a new page according to the groupwall method?
Here I just redirect the page. I want to make status update according to their semester.
Here is my code. Give me some code sample or suggest if this is not the right way to do that.
<form action="" method="get">
<textarea name="status" id="wall" cols="50" rows="2">
</textarea>
<input name="submit" type="submit" value="share" onclick="groupwall();"/>
</form>
<script type="text/javascript">
function groupwall(){
var semster=document.getElementById('txtsamp').value;
if(semster == "4-1"){
window.location ='4-1hpage.php';
//header("location: member-index.php");
}
else if(semster =="3-1"){
window.location ='3-1hpage.php';
}
else if(semster == "2-1"){
window.location ='2-1hpage.php';
}
else {
window.location ='1-1hpage.php';
}
}
</script>
you might be better off posting the textarea content to your server and storing it somewhere, even in the session. the reason I say this is that while you could pass it in window.location as a GET parameter, the textarea content can be arbitrarily long and might be too long to be passed as a GET parameter. you might consider an AJAX request to post the textarea to the content, perhaps performing validation, before redirecting to the next page of your application.
Just give your form an id -
<form id="share-form" ...
Set the action of the form instead of redirecting
var share_form = document.getElementById('share-form');
share_form.action = '....';
Submit the form
share_form.submit();
1) do a form post to another PHP page and
a) Store it in a database (If you will really use this in future also)
OR
b) Store it in Session Variable
OR
2) do an ajax post to a server page and
OR
a) Store it in a database
OR
b) Store it in Session Variable
Then from any PHP pages you can access these values.
Send as a parameter through the query string yoururl.com?variable=value
Through $_SESSION environment variable
Using a cookie (if turned on)
AJAX - store in database or text file before leaving page, and retrieve when entering new page
The simplest way to pass some sort of variable to a new page if the data isn't large is to put it in a query string in the URL and then have the new page parse it out of there and act on it. A query string is the part of the URL that follows a question mark like this:
4-1hpage.php?data=whatever
The query string values don't affect which page is called on your server, but can be used by either server or client to trigger different behavior in that page.
In the specifics of your particular question, it doesn't seem like you need to pass any data to the next page because you're already called a different page based on the results of the textarea, but you could pass the value like this if you needed to:
function groupwall() {
var semster=document.getElementById('txtsamp').value;
var url;
if(semster == "4-1") {
url ='4-1hpage.php';
} else if(semster =="3-1") {
url ='3-1hpage.php';
} else if(semster == "2-1") {
url ='2-1hpage.php';
} else {
url ='1-1hpage.php';
}
// encode the data for URL safety and make sure it isn't too long
window.location = url + "?semster=" + encodeURIComponent(semster.slice(0, 128));
}
If the textarea can be arbitrarily long and it needs to be capable of accepting very long values, then you will want to post it to your server and let the server decide where to redirect the user after the form post. When generating a new page, the server can then populate that page with whatever content is needed based on the values in the form post.
Other places that data can be stored temporarily so a future page can access it are cookies and HTML5 local storage. Cookies are somewhat restricted in size and it isn't efficient to put large data into cookies. HTML5 local storage isn't supported in all browsers so you generally need an alternate strategy as a fallback.

Categories

Resources