how to transfer values between html pages? - javascript

I'm opening new page from anothe like this:
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
the second html page looks like this:
<div class="row contractor_data__item">
<label for="code">Номер</label>
<input type="text" name="code" id="code" disabled/>
<input type="hidden" name="documentId" id="documentId">
<input type="hidden" name="actId" id="actId">
<input type="hidden" name="actCode" id="actCode">
</div>
on the page opening in the new window I have a few fields to fill. For example, I've filled "code" field on the first page and need to fill the "code" field in the page opened. How to do this?
the second part of question is that I've filled some fields on the page opened, like documentId and need to pass it to the first page I've called this one from on close, for example or on the field filled. How to perfrorm this?

In HTML5 you can use session to pass object from page to another:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key')
For further reference you can check here
Edit:
Sample Code:
Page1.html
<!DOCTYPE html>
<html>
<head>
<title>Page1</title>
<script type="text/javascript">
sessionStorage.setItem("name","ShishirMax");
var fName = sessionStorage.getItem("name");
console.log(fName);
function myFunction(){
window.open("page2.html");
}
</script>
</head>
<body>
This is Page 1
</br>
<button onclick="myFunction()">SendThis</button>
</body>
</html>
Page2.html
<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
</head>
<body>
This is Page 2</br>
<input type="text" name="txtName" id="txtName" value="">
<script type="text/javascript">
var fName = sessionStorage.getItem("name");
console.log(fName);
document.getElementById("txtName").value = fName;
</script>
</body>
</html>
Try the following code for the test purpose.

hi if you want transfer data in some page you can use localStorage our sessionStorage in js
difference between sessionStorage clear when you close browser and localstorage will be clear only if you ask it
go refer to documentation for sintax e.g :
you value is stak in 'data' variable in this e.g
var data;
sessionStorage.setItem('nameyourvar', data);
after you can take on other page with :
sessionStorage.getItem('nameyourvar')

Use a query string. That's what they're for. Dont' forget to wrap your values in encodeURIcomponent in case they contain any special characters.
window.open("somewhere.html?firstname="+encodeURIComponent(firstname)+"&lastname="+encodeURIComponent(lastname)+"");
In the new window you can get the values from the query string like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var firstname = getParameterByName('firstname'); // "Bob"
var lastname = getParameterByName('lastname'); // "Dole"
Function is from here.

Since other people are mentioning localstorage, you should know that localstorage isn't supported in all browser. If you're interested in using something like that (you should really use query strings instead) you can check out this cross browser database Library I wrote.
Set your items to the database on the first page
jSQL.load(function(){
jSQL.createTable("UserData", [{FirstName: "Bob", LastName: "Dole"}]);
jSQL.persist(); // Save the data internally
});
Get your items from the second page
jSQL.load(function(){
var query = jSQL.query("SELECT * FROM `UserData`").execute();
var row = query.fetch("ASSOC");
var firstname = row.FirstName;
var lastname = row.LastName;
});

You can use GET parameters.
When you're opening second page, pass all the data you want to pass as GET parameters in the url, for example :
var billhref = "whatever.html?code=your_code&parameter2=parameter2_value" ;
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
Make a JS function to get parameters on the second page :
function getParams() {
var params = {},
pairs = document.URL.split('?')
.pop()
.split('&');
for (var i = 0, p; i < pairs.length; i++) {
p = pairs[i].split('=');
params[ p[0] ] = p[1];
}
return params;
}
Then use this function to get url parameters like this :
params = getParams();
for( var i in params ){
console.log( i + ' : ' + params[i] );
}
This will return output like :
code : your_code
parameter2 : parameter2_value
Using PHP will help you get around this problem with even shorter code
For example, in PHP, to get the parameters code, you'll just have to write :
$code = $_GET['code'];
And it will give you assign a variable named code the value you have passed in the url against code parameter( your_code in this example ).

Related

how to use local storage in a proper way

i'm creating a form of inscription and i want to get info from a first page to show in a second one. I've tried to use local storage, but it doesn't work.
I've tried to test in the same page, which works, but when i try it with the localstorage, it doesn't work, and when i click on submit it reloads the page and nothing happens
Here is the code for the first page:
function rform()
{
document.getElemeentByName('insc').reset;
}
function client()
{
var sexe=document.getElemeentByName('gender');
var userT=document.getElementById('choice').selectedIndex;
var name = document.getEelementById('name').value;
localStorage.setItem('name',name)
if (userT[1] || userT[2] &&sexe[0].checked )
{
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice)
else
{
var res = document.getElementById('choice').value + 'e';
localStorage.setItem('choice',choice)
}
return false;
}
And the second page:
<span id="result"></span>
<script type="text/javascript">
document.getElementById("result").innerHTML= 'welcome '
+localStorage.getItem('name')+ ' you are '
+localStorage.getItem('choice');
</script>`
I get nothing in the second page, but expect to get a welcome message with the name and the user type
var choice = document.getElementById('choice').value;
localStorage.setItem('choice','choice')
This isn't setting the value of Choice into localStorage, this is simple setting the value of localStorage named Choice to the string "Choice".
Should be;
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice);

How can I save a cookie

I'm trying to save a cookie and then load it again
I have this code
<html>
<head>
<script>
var myCookies = {};
function saveCookies()
{
myCookies["_uuser"] = document.getElementById("user").value;
myCookies["_uuage"] = document.getElementById("age").value;
//Start Reuseable Section
document.cookie = "";
var expiresAttrib = new Date(Date.now()+60*1000).toString();
var cookieString = "";
for (var key in myCookies)
{
cookieString = key+"="+myCookies[key]+";"+expiresAttrib+";";
document.cookie = cookieString;
}
//End Reuseable Section
document.getElementById("out").innerHTML = document.cookie;
}
function loadCookies()
{
//Start Reuseable Section
myCookies = {};
var kv = document.cookie.split(";");
for (var id in kv)
{
var cookie = kv[id].split("=");
myCookies[cookie[0].trim()] = cookie[1];
}
//End Reuseable Section
document.getElementById("user").value = myCookies["_uuser"];
document.getElementById("age").value = myCookies["_uuage"];
}
</script>
</head>
<body>
User: <input type="text" id="user">
Age: <input type="text" id="age">
<button onclick="saveCookies()">Save To Cookies</button>
<button onclick="loadCookies()">Load From Cookies</button>
<p id="out"></p>
</body>
</html>
when I type an input for both name and age, and click on save to cookies,
and then clock on load from cookies, I got this "undefined" for both user and age!!
what's missing in my code, so I can save the cookie
For Chrome cookies can only be set, when the page is running on a webserver.
For example accessed via http://localhost/foo/bar.html or http://127.0.0.1/foo/bar.html
edit: you might check out as well this answer:
where cookie saved for local HTML file
I just tested it myself: it works with Firefox.
Otherwise it would be better for testing such cases, to put up a local webserver like apache
I have tested your code from a web server and it works fine.
You must load it from a web server, rather from the local file system.
JSFiddle is here if you want to prove it for yourself.
https://jsfiddle.net/brx5ropp/
Note that due to JSFiddle limitations I had to move the click triggers for the buttons to code like this:
document.getElementById("load").addEventListener("click", loadCookies);
document.getElementById("save").addEventListener("click", saveCookies);
...but that is irrelevant to my answer!

How do i make my submit answer continue stacking on top of each other

I am currently doing a school project and i need to stimulate a server side application. What i am substituting it with is "Local Storage" but i have an issue. I am able to have the text in my "Text box" stack on top of each other once user have submitted their question. Once they reload, the data will still be displayed. But i do not know how to stack on top of it AGAIN after they reload. Below is my testing code
<!doctype html>
<html>
<head>
<body onload="display()">
<input type="text" id="Name"></input>
<input type="submit" id="submit" onclick="SavetoStorage()"></input>
<p id ="hoho">
</p>
<script>
var name;
var groupOfName = ["Hello", "Chicken", "Pork","Beef"];
function SavetoStorage() {
var name = document.getElementById("Name").value;
groupOfName[groupOfName.length] = name;
var newone = groupOfName;
document.getElementById("hoho").innerHTML = newone;
localStorage.groupOfName = newone;
}
function display() {
var groupOfName = localStorage.groupOfName;
document.getElementById("hoho").innerHTML = groupOfName;
}
</script>
</head>
</body>
</html>
You need to be dynamically loading the groupOfName variable like so:
var tmp = localStorage.groupOfName; //this is a string
var groupOfName = Array.from(tmp); //turn it into an array
Hopefully this helps to point you in the right direction
You can use the setItem method from localstorage.
It uses 2 parameters:
a key and a value
so you can do something like this:
var inputValue = document.getElementById("Name").value;
localStorage.setItem("name", inputValue);
The above code sets the key "name" and that key holds the inputValue
So now you can retrieve the value by calling another local storage method called getItem:
var retrieveValue = localStorage.getItem("name");
The above code retrieves the item, and what does that item holds? the value from the input, so now you can add it to your html as you wish
So that's the basics but as you only have 1 input the value will be getting overwrited, and LocalStorage doesn't supports arrays but there's a workaround so you can use arrays, it goes something like this:
//this first part converts your array to string
localStorage.setItem("names", JSON.stringify(names));
//The second part returns your item and coverts it to an array again
var storedNames = JSON.parse(localStorage.getItem("names"));

Can Not Set Value of DOM Element Unless New Value Is Strictly Numeric

DISCLAIMER: total beginner with regards to browser extensions and javascript.
BACKGROUND:
I'm trying to develop a proof-of-concept Chrome extension that picks up the text from the input fields in the HTML form of the web page loaded into one tab, and enters the same text on analogous fields of the page in another tab.
In my particular example, the source page is a minimal, local HTML file with two input fields ("user name" and "password"), and the destination is the login page for Apple's Developer Website (https://developer.apple.com/account/).
Reading the official guides and questions here, I've put together some code that seems to work.
THE PROBLEM:
Only text consisting of digits (e.g.: "111111") gets copied from one tab to the other. As soon as my input field contains letters (e.g.: "111111a"), nothing happens.
This is the source page (local file:///):
<html>
<head>
<title>Source Page</title>
<meta charset="utf-8" />
<script src="popup.js"></script>
</head>
<body>
<form>
<input id="accountname_src" name="appleId" placeholder="Apple ID" /><br />
<input id="accountpassword_src" name="password" placeholder="Password" />
</form>
</body>
</html>
The destination HTML (Apple's page) has similar input fields with element ids of accountname and accountpassword, respectively.
My extension's script is as follows:
document.addEventListener('DOMContentLoaded', function(){
// The button in the browser action popup:
var button = document.getElementById('autofill');
var sourceTabID = null;
var destTabID = null;
// Get the SOURCE tab id:
chrome.tabs.query({'title': 'Source Page'}, function(tabArray){
sourceTabID = tabArray[0].id;
});
// Get the DESTINATION tab id:
chrome.tabs.query({'title': 'Sign in with your Apple ID - Apple Developer'}, function(tabArray){
destTabID = tabArray[0].id;
});
if (button !== null){
button.addEventListener('click', function(){
// Get entered text from Source page:
chrome.tabs.executeScript(sourceTabID, {file: "read_input.js"}, function(results){
var credentials = results[0];
var userName = String(credentials[0]);
var password = String(credentials[1]);
// Pass values to Apple login page:
var insertUserNameCode = "document.getElementById('accountname').value = " + userName + ";"
var insertPasswordCode = "document.getElementById('accountpassword').value = " + password + ";"
var autofillCode = insertUserNameCode + insertPasswordCode;
chrome.tabs.executeScript(destTabID, {code:autofillCode});
});
//window.close();
});
}
});
of course, the contents of read_input.js are:
var userName = document.getElementById("accountname_src").value;
var password = document.getElementById("accountpassword_src").value;
var attributes = [userName, password];
attributes // (Final expression, passed to callback of executeScript() as 'results')
It feels like there could be a type inference problem somewhere, but can't tell where.
Bonus Question:
I can read the input fields in the source page using an external script (read_input.js above) and the method chrome.tabs.executeScript(..., file:...; but when I try to write the values to the destination tab using a similar approach, the script does not run (that is why I'm using chrome.tabs.executeScript(..., code:... in my code). Any idea what can be happening?
Silly me (again)... Some console.logging led me in the right direction...
I was not escaping the value in the script; these lines:
var insertUserNameCode = "document.getElementById('accountname').value = " + userName + ";"
var insertPasswordCode = "document.getElementById('accountpassword').value = " + password + ";"
...should be:
var insertUserNameCode = "document.getElementById('accountname').value = '" + userName + "';"
var insertPasswordCode = "document.getElementById('accountpassword').value = '" + password + "';"
(added single ticks around the values)
...so that the code ends up as:
document.getElementById('accountname').value = '111111a';
...instead of:
document.getElementById('accountname').value = 111111a;
Still not sure why a numbers-only value works, though.

JavaScript - How do I open a new page and pass JSON data to it?

I have a page called search.jsp. When the user selects a record and the presses an edit button, I would like to open a new page (in the same window) with the record data (that is stored in a json object and passed to the new page). How do I use Javascript (or jQuery) to open a new page and pass the JSON data?
If the two pages are on the same domain, a third way is to use HTML5 localStorage: http://diveintohtml5.info/storage.html
In fact localStorage is precisely intended for what you want. Dealing with GET params or window/document JS references is not very portable (even if, I know, all browsers do not support localStorage).
Here's some very simple pure JavaScript (no HTML, no jQuery) that converts an object to JSON and submits it to another page:
/*
submit JSON as 'post' to a new page
Parameters:
path (URL) path to the new page
data (obj) object to be converted to JSON and passed
postName (str) name of the POST parameter to send the JSON
*/
function submitJSON( path, data, postName ) {
// convert data to JSON
var dataJSON = JSON.stringify(data);
// create the form
var form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('action', path);
// create hidden input containing JSON and add to form
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", postName);
hiddenField.setAttribute("value", dataJSON);
form.appendChild(hiddenField);
// add form to body and submit
document.body.appendChild(form);
form.submit();
}
Use some PHP like this on the target page to get the JSON:
$postVarsJSON = $_POST['myPostName'];
$postVars = json_decode( $postVarsJSON );
Or, more simply for JavaScript:
var postVars = JSON.parse( <?php $_POST['myPostName']; ?> );
Assuming the two pages are on the same domain, you can use the returned object created by window.open() to access (and edit) the window object of a newly opened window.
Hmm, for example, you have object
var dataObject = {
param : 'param',
param2 : 'param2'
};
You can translate it into string, using JSON.stringify method
var dataObjectString = JSON.stringify(dataObject);
Then you should use Base64 encoding to encode you data (base64 encode/decode methods can be easely found in search engines)
var dataObjectBase64 = base64encode(dataObjectString);
You will get something like this
e3BhcmFtIDogJ3BhcmFtJyxwYXJhbTIgOiAncGFyYW0yJ307
Then you can pass this string as a parameter:
iframe src="http://page.com/?data=e3BhcmFtIDogJ3BhcmFtJyxwYXJhbTIgOiAncGFyYW0yJ307"
Finally, reverse actions on the loaded page.
You can create "on the fly" a form with a hidden/text input value this will hold the json value, then you can submit this form via javascript.
Something like this...
Im using JQUERY AND UNDERSCORE(for template purpose)
this is the template
<form method='<%= method %>' action="<%= action %>" name="<%= name %>" id="<%= id %>" target="_blank">
<input type='hidden' name='json' id='<%= valueId %>' />
</form>
you can then post use it on javascript
function makePost(){
var _t = _.template("use the template here");
var o = {
method : "POST",
action :"someurl.php",
name : "_virtual_form",
id : "_virtual_form_id",
valueId : "_virtual_value"
}
var form = _t(o); //cast the object on the template
//you can append the form into a element or do it in memory
$(".warp").append(form);
//stringify you json
$("#_virtual_value").val(JSON.stringify(json));
$("#_virtual_form_id").submit();
$("#_virtual_form_id").remove();
}
now you dont have to be worry about the lenght of you json or how many variables to send.
best!
If the the JSON is small enough you can just include it as a GET parameter to the URL when you open the new window.
Something like:
window.open(yourUrl + '?json=' + serializedJson)
Assume if your json data
var data={"name":"abc"};
The page which sends JSON data should have the following code in the script tag.
$.getJSON( "myData.json", function( obj ) {
console.log(obj);
for(var j=0;j
<obj.length;j++){
tData[j]=obj;
//Passing JSON data in URL
tData[j]=JSON.stringify(tData[j]);
strTData[j]=encodeURIComponent(tData[j]);
//End of Passing JSON data in URL
tr = $('\
<tr/>
');
//Send the json data as url parameter
tr.append("
<td>" + "
" +Click here+ "" + "
</td>
");
}
});
The page which receives the JSON data should have the code.
<html>
<head></head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<body>
<p id="id"></p>
</body>
<script type="text/javascript">
function getQuery() {
var s=window.location.search;
var reg = /([^?&=]*)=([^&]*)/g;
var q = {};
var i = null;
while(i=reg.exec(s)) {
q[i[1]] = decodeURIComponent(i[2]);
}
return q;
}
var q = getQuery();
try {
var data = JSON.parse(q.jsonDATA);
var name=data.name;
console.log(name);
document.getElementById("id").innerHTML=name;
} catch (err) {
alert(err + "\nJSON=" + q.team);
}
</script>
</html>

Categories