Pass Value from one page to another page - javascript

I want to pass form value from one html page to another html page.
I wonder Is that possible to pass values between html page not using server side code.
And if not, how can i pass values?
(I prefer to not use server side...)
Here is some my project code :
First HTML page
<form id="myForm" method="post" action="secondHTMLPage URL">
<input type="hidden" id="UserID" name="UserID" value="12345">
</form>
<script type="text/javascript">
$("#myForm").submit();
</script>
Second HTML page
<script type="text/javascript">
// In here, I want to retrieve my $("#myForm")'s data from First Page.
</script>

You can try with Window.sessionStorage or Window.localStorage.
The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.
localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.
Set value in one page
localStorage.setItem('myCat', 'Tom');
//using sessionStorage
//sessionStorage.setItem('myCat', 'Tom');
Get the value in other page
var cat = localStorage.getItem('myCat');
//using sessionStorage
//var cat = sessionStorage.getItem('myCat');

Related

How should i store newly created elements in JavaScript?

I running in some issues with my code below. I have achieved to create a new element and add it to the Option list. Now a whenever i refresh the page the new element will disappear from the list.I am not familiar how cookies or session works in JavaScript. But how could i store those element and whenever i create a new element to be able to be in the Option list even after refreshing. Sorry for my English , and thank you for the help in advance. My code is below as you can see.
<select name="name" id="name">
<option value="burim" class="someName">burim</option>
<option value="eliot" class="someName">eliot</option>
<option value="saska" class="someName">saska</option>
</select>
<br><br>
<input type="text" id="add">
<input type="submit" name="submit" value="ADD list" id="btn">
<p class="output"></p>
<script>
var btn=document.getElementById("btn");
btn.onclick=function(){
var n =document.getElementById("name");
var list=document.getElementById("add").value;
var listArray={};
var newOption=document.createElement("option");
listArray=n;
newOption.className="someName";
newOption.innerHTML=list;
newOption.value=list;
n.appendChild(newOption);
}
</script>
There is three ( main ) way to store client side data in Javascript.
The cookies are used to store data that is accessible to the server, ex: JWT authentication token.
The other two are Session storage and local storage. I've never learn the difference between the two but here is a good question about it.
In your case, I would suggest using localStorage. It is very easy to use and will be available until clear programmatically or by the user.
You can add data to the localStorage using
window.localStorage.setItem('key', value)
and retreive it using.
window.localStorage.getItem('key')
You should only keep minimum data in the localStorage, don't store your HTML. Store only enough data to rebuild it once you need your information.

Having problems with my very basic HTML static page generator

I am trying to create a new HTML page from a form and some javascript. The form is much longer than this, but I figured that if I gave you guys 2 text inputs I can take it from there. I am running into a problem where I cannot retrieve the value of my forms and send it on to my new page. My new page won't show anything because it thinks that my forms are null, or that they don't exist possible. Which is probably why it returns undefined. I'm completely stuck here and I have no idea what to do as far as setting up the new page from my form goes.
I need help with getting newPage.html to display my title and subtitle.
Here is js:
var title = document.createElement("h1");
var titleForm = document.getElementById("title");
var subTitle = document.createElement("h3");
var subtitleForm = document.getElementById("subtitle");
var myDiv = document.getElementById("container");
function getElements() {
//set the title
var titleNode = document.createTextNode(titleForm.value);
title.appendChild(titleNode);
//set the subtitle optionally
var subtitleNode = document.createTextNode(subtitleForm.value);
subTitle.appendChild(subtitleNode);
}
Here is the original HTML page:
<body>
<h1>Create A New Webpage Using This Form</h1>
<form id="form">
<label>
Title:
<input type="text" name="title" id="title" value="title">
</label><br><br>
<label>
Subtitle:
<input type="text" name="subtitle" id="subtitle" value="subtitle">
</label><br><br>
<input type="button" value="Generate Page" onclick="window.open('newPage.html');">
</form>
<script type="text/javascript" src="pageGenerator.js"></script>
<script>getElements();</script>
</body>
Here is the page that I want to create:
<body>
<div id="container">
<ul id="myList"></ul></div>
<script type="text/javascript" src="pageGenerator.js"></script>
<script>setElements();</script>
</body>
I'm not looking for you to complete this for me, but just a little bit of guidance. Thanks.
It sounds like you want JavaScript on one page to read from JavaScript on another page. That's not possible on its own. You can't define var a = 1 on somePage.html then read that variable when the user's browser loads newPage.html.
You'll need to involve something else, such as the URL or local storage: https://stackoverflow.com/a/35027577/5941574
Query Parameters
One option is to make a GET request to newPage.html with whatever values you want include as query parameters in the request. Then newPage.html will contain a script that parses the URL to get the parameters and builds and inserts HTML into the document based on the values it finds in the URL.
Local Storage or Cookies
This works in pretty much the same way as the other method except instead of getting your values from the URL, it is saved to the user's computer with either cookies or local storage.
Server Side
A third option of course is to send the user's selections to a server and have the server build and serve the resulting page.

Sending form data to HTML Page and Retrieving it with Javascript without any PHP/Python

I've read a few articles and a question thread on sending form data to another html page, but the solutions didn't solve the issue for me.
Basically, I have a form with a bunch of data:
<form id="registration" name="registration" action="register.html" method="POST">
In register.html, I tried accessing an input text field with id and name as "username" with this:
var x = document.getElementById("registration").elements.namedItem("username").value;
The console stated that it cannot read property of null. How can I access these values with Javascript only? Frameworks are fine but not PHP /Python.
I'm sure that none of this can be safe, so use caution.
If you don't care about the info being super obvious, then you can make the action of the the form the new page you want, and the method can be 'GET'.
EDIT: I should mention this will go through the url, as such
domain.com?someKey=someValue&someOtherKey=someOtherValue
On the new page, you can parse the url for the query string for everything.
You can grab that stuff out of the 'href' property from the location.
window.location.href
// * Credit for this puppy goes to theharls, nice and fast
var params = window.location.search.slice(1).split("&");
//=> ["say=Hi", "to=Mom"]
Another option on (modern ?) browsers is Local Storage.
Use javascript to to set things like,
localStorage.setItem('foo', 'bar');
Great reference for local storage here.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
I ran into something like this the other day. Turns out you can just get the values with jQuery.
var userName = $("input[type=text][name=username]").val();
Just put it into a function that's called in the form's onsubmit.
<script>
function getFormData() {
var userName = $("input[type=text][name=username]").val();
// Do what you want with the data
return true;
}
</script>
<form id="registration" name="registration" action="register.html" onsubmit="return getFormData();" method="POST">
<input type="text" name="username" />
</form>
However, this doesn't keep the data when you load the next page. To do that, just commit the value into sessionStorage.
function saveFormData() {
var userName = $("input[type=text][name=username]").val();
sessionStorage.setItem("user", userName);
return true;
}
And then on the next page (the one you're calling resgister.html) you can use this code to retrieve it.
var userName = sessionStorage.getItem("user");
I hope this helps!
A webpage can't receive POST data. Send it using method="GET" instead, then retrieve it on the target page using JS as follows:
<script>
var params = window.location.search.slice(1).split("&");
// params is ["say=Hi", "to=Mom"]
</script>
You can easily target the selectors by querySelector. The value will no longer be null.
<form id="registration" name="registration" action="register.html" method="POST">
<input type="text" class="username" value="abcdefg">
</form>
<script>
var x = document.querySelector("#registration .username").value;
//check your code in devtools
console.log(x);
</script>
jsfiddle

Everytime a page is refreshed i lose data, but i want to keep the last textbox value

i was working on a program that i wrote in php, all is fine, the problem is the html page:
it has 1 textbox and 1 button.
In the textbox i have to write a link
when i load the page it clicks the button automatically, so i can use the php program, then it return back to the html page..
$(document).ready(function(){$('#printbuttoncustomer').trigger('click');});
The links that i need to use are always the same, except the number, example:
http://www.wowhead.com/npc=56843 --- http://www.wowhead.com/npc=56844 etc..
the problem is that everytime the page is loaded, it start to use always the link and can't go on with the next link with the new value
how can i solve this problem?
I think that i could use a txt file to save the last link i used, so in the html i can check the last link in the txt file and set the next value in the textbox.. But don't know how to do.
the code to start is this
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="jquery-2.0.2.js"></script>
</head>
<body>
<form method="POST" action="parser.php">
<input type="text" id="testo" name="testo">
<input type="submit" id="button" >
</form>
<script>
$(document).ready(function(){
$('#button').trigger('click');
});
</script>
</body>
</html>
convert the html page to php. When returning to this page from "parser.php", send back a response with next link and save that in the text field.
You can save the link in a session and not a file :
$_SESSION['URL'] = "Your URL HERE"
next time you read it like this:
var $MyUrl = $_SESSION['URL'];
Please check this link for more on PHP Sessions.
Since you have to persist the information of your last clicked page so that next time you load the page it goes to next page.
You can do this by two ways:-
*Server Side Change:-
You can implement sessions to store the information, where you store the last URL.
*Client Side Change:-
After HTML5 there are a lot of browser storage is available. So you can use local storage, it stores site specific data in browsers persistent memory. Also there is session storage available.Check this page for HTML5 Web Storage.

Javascript global variable does not persist when navigate to another page (which also uses same js file) [duplicate]

This question already has answers here:
Persist variables between page loads
(4 answers)
Closed 7 years ago.
I have shared js code like this in angus.js
var g_colour;
function getcolour() {
return g_colour;
}
function setcolour(colour) {
g_colour = colour;
}
Which is accessed by html pages 1 and 2 like this:
1.html:
<html>
<head>
<title>Global javascript example</title>
</head>
<body>
Page2
<script src="angus.js"></script>
<form name="frm">
<input type="button" value="Setblue" onclick="setcolour('blue');" />
<input type="button" value="Setyellow" onclick="setcolour('yellow');" />
<input type="button" value="getcolour" onclick="alert(getcolour());" />
</form>
</body>
</html>
2.html:
<html>
<head>
<title>Global javascript example page 2</title>
</head>
<body>
Page1
<script src="angus.js"></script>
<form name="frm">
<input type="button" value="Setblue" onclick="setcolour('blue');" />
<input type="button" value="Setyellow" onclick="setcolour('yellow');" />
<input type="button" value="getcolour" onclick="alert(getcolour());" />
</form>
</body>
</html>
If I set a colour in one page and navigate to page 2, and THEN access the colour, it returns undefined. ie I it seems that a new instance of g_colour is created on loading a new html page.
I want to be able to access a sort of top-level variable which I can set in page 1 and access in page 2. How can I do that in Javascript?
JS variables never have been persistent, but there are two ways around this:
Cookies
Storage
Cookies are supported in all but the most ancient browsers, but they can be very unwieldly and difficult to use. On top of that, your browser sends cookies to the server with every pageload, so if it's only used by JavaScript then it's very inefficient.
Instead, you should probably look at the Storage option.
Saving an item is as simple as localStorage.itemname = value; Reading is as easy as localStorage.itemname, and deleting is as literal as delete localStorage.itemname
These values are saved across pageloads, but not sent to the server.
Use localStorage:
localStorage.setItem('name', 'value');
var something = localStorage.getItem('name');
setItem on your first page, then getItem on your second.
The localStorage persists across pageloads, as opposed to "normal" JavaScript variables.
"Normal" variables are initialized as soon as the JS file is loaded (And runs), but are destroyed when the file unloads, so when the user leaves a page.
You could also use Cookies, but they're a bit of a pain to work with in JS, since they're stored in a string like:
'name=value; name1=value1; name2=value2';
Each page request will request the script and execute its copy of it, even if the request stops at the client because of the cache, the current page still executes it from scratch. They are working with the same code, yes, but different instances (i.e. you have two copies of that variable in two different contexts).
The problem is that your page 1 is loading the JavaScript file and your page 2 is loading it again therefore whatever you have set in a variable on that JS file will be lost when page 2 is loaded since page 2 will initialize again the JS file. If you want you can use cookie to store the value or if it simple to you combine page 1 and page 2 but put them in a different div and show/hide the div according to your logic.

Categories