Getting values from html form as JavaScript variables - javascript

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; ?>";

Related

How can I reuse an ordinary html form whose action takes one to a php file?

I’m an amateur and can’t solve what I would imagine is a frequent problem in html/php forms processing.
Let’s say you have a simple html form which you want use over and over in one sitting and you want to keep track in a variable of how many times you’ve submitted the form. You need, let’s suppose, to send the form to a php file for various reasons (perhaps to put names into a data base). The trouble is that after you’ve submitted the form to the php file, which processes the form data and redirects back to the html file, doing so will reset your count variable to O -- and reset other variables to their original value -- which I dont want.
Here’s the html file, call it collect_and_post_data.html.
<!DOCTYPE html>
<html>
<body>
<form id="formID" method="post" action="process_form_data.php">
  Enter first name: <input type="text" name="fname"><br>
  Enter last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">
</form>
<script>
var noOfTimesFormSubmitted = 0;
document.getElementById("formID").addEventListener("submit", myFunction);
function myFunction() {
  alert("The form was submitted");
  alert("noOfTimesFormSubmitted: " + noOfTimesFormSubmitted);
  noOfTimesFormSubmitted++;
}
</script>
</body>
</html>
And here’s the php file,  process_form_data.php.
<?php
echo $_POST["fname"].' '.$_POST["lname"];
//do other stuff
header ("Location: collect_and_post_data.html");
die();
?>
How do I get the php file, when it redirects to collect_and_post_data.html, to keep noOfTimesFormSubmitted from startingagain at 0, and other variables that have changed on submission from returning to there original value?
Alternatively, is there some way one can persuade the php file to simply drop out of the picture after it has done its job after each form submission, leaving the user back in the html file?
I've tried using just one file, the form action being  but this doesn't solve the problem. When the second iteration of the form appears, all global javascript variables that were changed when the .form is first submitted go back to their original values.
Help would be appreciated.
you can use the PHP session variable to update the noOfTimesFormSubmitted
$_SESSION['noOfTimesFormSubmitted']=+1
something above like this will enable your number of time form is submitted will store in session variable until the session is cleared

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!

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.

Is it possible to get $_FILES["inputID"]["tmp_name"] from a file field using javascript?

I have an input field:
<input type="file" id="inputID" name="file">
When a button is clicked to submit, a JavaScript function will run (url: upload.php). I need to be able to access $_FILES["inputID"]["tmp_name"] from this input field so that I could use it on upload.php as,
move_uploaded_file($_FILES["inputID"]["tmp_name"], $target_file)
Is this possible?
At the moment, I get an error:
Notice: Undefined index: inputID
Any help would be very much appreciated.
Thanks so much! :-)
move_uploaded_file() is a php function, running on a PHP-based server-side application.
It is handled by PHP when your form has been submitted.
You cannot access it from JavaScript before it has been sent, whatever would be the way you would submit it, both asynchronously with an XHR Request, or directly submitting the form to its handler route.
you can access it after it is submitted, although I don't see why you should:
<?php
...
$tmpname=$_FILES["file"]["tmp_name"]
...
?>
...
<script>
var tmpname = <?=$tmpname?>
...
</script>
...
I'm not clear on what you are trying to do. If you want some ajax upload functionality It's better to use a js library.

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

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.

Categories