How do I pass Javascript variable to <jsp:setProperty> and JSTL? - javascript

How do I pass Javascript variable to and JSTL?
<script>
var name = "john";
<jsp:setProperty name="emp" property="firstName" value=" "/> // How do I set javascript variable(name) value here ?
<c:set var="firstName" value=""/> // How do I set javascript variable (name) value here ?
</script>

You need to send it as a request parameter. One of the ways is populating a hidden input field.
<script>document.getElementById('firstName').value = 'john';</script>
<input type="hidden" id="firstName" name="firstName">
This way you can get it in the server side as request parameter when the form is been submitted.
<jsp:setProperty name="emp" property="firstName" value="${param.firstName}" />
An alternative way is using Ajax, but that's a completely new story/answer at its own.
See also:
Communication between Java/JSP/JSF and JavaScript
Your previous question regarding the subject
Your other previous question regarding the subject
If you can't seem to find your previously asked questions back, head to your user profile!

AFAIK you can't send data from JavaScript to JSTL that way. Because the JSTL tags are handled serverside, so the <jsp:> tags will be parsed on the server and replaced by HTML. So the <jsp:> tags won't be a part of the response that is sent back to the client; it will consist only of HTML/text. Therefore you can't access the <jsp:> tags from JavaScript, because they won't exist in the document.
Edit: sorry, the <jsp:> tags wasn't visible.

<script>
var name = "<jsp:getProperty name="emp" property="firstName" />";
</script>
The JSP code executes before the JavaScript so by the time the JavaScript gets processed the tag will be replaced with the contents of emp.firstName.

Related

Pass Javascript variable to another page via PHP Post

I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!

Getting values from html form as JavaScript variables

i want to capture input variables sent via form from one page to another.html page and obtain these values as JavaScript variables. Can this be done.
This is my form;
<form action='another.html' id='form' data-ajax='false'>
<input id='sent_by' value='tom'/>
<input type='submit' value='Submit'/>
</form>
And in my another.html i tried to get the values as;
var sent_by = $.session.get("sent_by");
But i am not able to get the values. All help is appreciated.
You can use the browser's localStorage to achieve this. Before submitting and going to the other page store all the values of the form in the localStorage and you can access it on the other page:
Page1.html
Field Name = "name" <input type="text" name="name" id="name" />
Read the value and store it to localStorage
localStorage.setItem('name', document.getElementById('name').value);
and so on.
You can make a function in JavaScript that saves all the fields of the form in localStorage on / before submit.
To read these values on the other page:
Page2.html
Value stored for key name can be get using the following JavaScript:
localStorage.getItem("name");
NOTE
the page1.html and page2.html should be in the same domain for you to access the localStorage.
Read more about localstorage at https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
Have you tried using Window.localStorage? It's similar to sessionStorage but with no expiration date. So, be sure to clear it once the browsing session ends.
I think the answer provided by #Shakti Phartiyal is probably the most practical and a sweet trick I might add. The main reason I'm writing this post is because I had also taken a long path of using javascript to pass along this kind of information. It resulted in me bewildered at how powerful PHP can be for some tasks that you dedicated javascript to do. (Yea I know some javascript wizards out there can do everything with it, I'm just talking about basic programming tho). So if you wondered what the PHP way of passing this around:
Your modified html form:
<form action='another.html' id='form' data-ajax='false' method='post'>
<input id='sent_by' value='tom' name='uname'/>
<input type='submit' value='Submit'/>
</form>
and then in "another.php" you would have this to retrieve the input from the form:
<?php
$uname= htmlspecialchars($_POST['uname'];
?>
Great. But how to make this php variable into javascript?
Ah, the fun part. You're going to write javascript to your webpage with php - you do something like this:
var uname = "<?php echo $uname; ?>";

Is it bad practice to pass php variables into values of html input tags?

The thought of making yet another get request and yet another php file is annoying to me... so I've been using this method:
<input class='hidden' id='dataIwant' value=' <?php echo $_SESSION["bigObjectArray"] ?>" />
Is this bad practice? What do you think?
IMHO, session variables might be dangerous to display in the client side. Only part of them such as indexes, strings which the user already knows should be shown to the user. If the session variable contains something like user password, session token etc., it should be hidden.
About your question, it changes when where you want to use this data. If it's only for passing it inside the form to another PHP page, you don't need to do this, as it will still be available in the form processing page.
If you want to use it inside the javascript code in the client side, you can json_encode it and assign it to a javascript variable.
<script type="text/javascript">
var myBigJSON = <?php echo json_encode($_SESSION["bigObjectArray"]);?>;
var myBigArray = $.parseJSON(myBigJSON);
</script>
I think this example speaks for itself:
<?php
session_start();
$_SESSION['bigObjectArray'] = "\" /><script>alert('Hi!')</script><input type=\"hidden";
?>
<input class="hidden" id="dataIwant" value="<?php echo $_SESSION["bigObjectArray"] ?>" />
output:
<input class="hidden" id="dataIwant" value="" /><script>alert('Hi!')</script><input type="hidden" />
Make sure to validate and filter the data you are echoing. Be paranoid, always.
It's a bad pratice if you do not escape it (htmlentities or htmlspecialchars).
It's a bad practice if user have no reason to change this field.
It's a bad practice for multi-tab browsing, since it's SESSION stored (concurrent pages writing/reading that value will fail).
It's a good practice if you html escape the value, if the user can change that field (and if you check it on the treatment page) and if it avoids storing that value in SESSION.

Retrieve variable name from an HTML site

I am trying to retrieve simple javascript variable (which is written to a File Systems Object) from a website which is served by an apache host on my ubuntu laptop.
So I have the function that writes the variable set up as follows:
<script type ="text/javascript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/home/lex/Downloads/goal.txt", true);
s.writeline(document.passForm);
s.Close();
}
</script>
and the section that takes the user input from the html website is
<div id="bot-right">
<form onsubmit="WriteToFile(this['goal'].value)">
<a align = "left"> <b><Strong>Enter a Goal name</Strong></b></a><br>
<input type="text" name="goal"> <br>
<input type="submit" value="Send Zeus">
<br>
</form>
</div>
For some reason, when I type in variable names to the form on the website, the file goal.txt gets created in the directory, /home/lex/Downloads/, but nothing gets written to it.
I also noticed that when I delete the goal.txt file and rewrite the variable from the html website, the file doesn't always get created.
I am not a JavaScript person and I am at a loss as to what I may need to fix this.
My intention is to get the variable written to the text file and have a processing c++ file process the variable.
Would someone be kind enough to lend an insight?
Thanks!
one way to do it is just calling the function without parameters and just getting the input value like this:
adding and id or a class to your input to get that specific value:
document.getElementById('goal').value
document.getElementByClass('goal').value
Or getting the value by name:
document.querySelector('[name="goal"]').value;
EDIT1
You could add a console.log to check if the value is beign passed correctly like this:
var inputValue = document.querySelector('[name="goal"]').value;
console.log(inputValue);
And if the value is being passed then the problem is your writeline or in the creation of the document
EDIT2
I just tested it and retrieving the value works just fine, so the problem must be in your document writing method, please check this documentation it can help you and i think is a better solution:
http://www.html5rocks.com/en/tutorials/file/filesystem/

how to assign javascript value to jsp variable in jsp page

I have a text field, I need to send these text value to the same page which is in jsp .
I just want to assign javascript value to jsp variable.
You can't. JSP runs on the server, Javascript runs on the client, so when Javascript runs the JSP variable doesnt exist anymore.
Consider using AJAX.
You could set a hidden field.
Put this in your JSP form:
<input type="hidden" id="foo" name="foo" />
Execute this script whenever you want to fill the field:
document.getElementById("foo").value = "some value";
When you submit the form, it'll be available as follows in the servlet:
String foo = request.getParameter("foo"); // "some value"
// ...
See also:
Communication between Java/JSP/JSF and JavaScript

Categories