How to pass a variable from current window to another window - javascript

First Page
<button onclick="refereceid_Transfer()">Try it</button>
<script>
function refereceid_Transfer() {
alert('test');
var referenceid = "jggd154278";
referenceid = btoa(referenceid);
//sessionStorage.setItem("sent", referenceid);
window.open("second.jsp", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
}
</script>
Second Page
<p id="s1"></p>
<script>
$(document).ready(function(){
// var a = sessionStorage.getItem("sent",id);
alert(a);
});
</script>
I need to pass my reference id from one window to another window. I tried use session storage and local storage to pass variable and i have failed in both condition. is there new suggestion that i can pass my reference id to new window.
Thanks

You can try localStorage for this.
Add item which you want to pass on another page:
localStorage.setItem("key", "value");
On another page you can access through:
localStorage.getItem("key");
You can store object data as well in localStorage. Note that clear localStorage if you're storing some sensitive information.
And simpler option is to use query parameter, but I think you're not okay with it.
Or you can use sessionStorage:
sessionStorage.setItem("key", data);
window.open("page_url","_blank");
on another page use:
$(document).ready(function(){
var data = sessionStorage.getItem("key");
console.dir(data);
});
Note: The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.

You can do it with local storage or you can pass it in query parameters and read the query parameters at 2nd page.
If you are doing server side rendering you can also use session storage.

Related

Passing section of query result into session variables with Javascript

I'm having trouble passing the result of a query into a session variable, I think that the easiest way to do this is through Javascript. I have the query result showing but they will not pass to the session variable. At the end of each query resultant row, I have an add button that will activate the JS function to add to the session variable.
Query Result:
echo '<tr><td>'.$products['Name'].'</td><td>£'.$products['Price'].'</td><td>'.$products['Category'].'</td><td><img src="'.$products['Image'].'" width=100px /></td><td>'.$products['ProductID'].'</td><td><button onclick="setProduct('.$products['ProductID'].')">Add to Basket</button></td></tr>';
JS Function:
function setProduct(x){
var productID = x;
'<%Session["ProductID"] = "'+$products['productID']+'";%>';
Code displaying contents of session variable:
echo $_SESSION['ProductID'];
$_SESSION is a server-side variable. You'd most likely want to set a $_COOKIE instead. Those are accessible on the client-side.
In addition to the answer posted, you can create a jQuery post request (or you can use AJAX) and send the JS session as value to a PHP file where you can access that value and create the corresponding PHP session.
Let's say, your JS function:
function setProduct(x){
var productID = x;
'<%Session["ProductID"] = "'+$products['productID']+'";%>';
// ...
$.post('example.php', { session_name: YOUR-SESSION-NAME, session_value: YOUR-SESSION-VALUE });
example.php:
if (isset($_POST['session_name']) && isset($_POST['session_value'])) {
$_SESSION[$_POST['session_name']] = $_POST['session_value'];
}
This is not taking into consideration security issues you might face. You should encrypt your data before sending it.

How to pass a variable to a new page and insert it to a textbox?

I am trying to transfer a variable from one page using this code:
Edit
to the page login.html, and insert the variable(asdf in this example) to a textbox in the new page.
I have tried this code:
function NameFunction(name) {
document.getElementById("username").value = name;
}
It is not working. I think it doesn't work because thats another page.
If you want to pass parameters to another page you can put them using query string:
Edit
To get parameter on the login.html page you can use jQuery as it described here: Get escaped URL parameter
you can try using localStorage.
In you're onClick method, save the data you want to store in localStorage
localStorage.setItem(key,value);
When the new page loads, in the onLoad (ready function if using jquery) method get the data from localStorage and set it in the textbox
you can find more about localStorage in the following links
Storing Objects in HTML5 localStorage
http://www.w3schools.com/html/html5_webstorage.asp
and many more are available online

Adding extra variables to a URL

Using JavaScript I managed to add a variable to a page and used $_GET on the new page to use the variable to perform queries. This first implementation worked fine as I was only using one variable. However I need to use two variables now and I'm running into some problems while doing it. If I combine both variables in the first page like shown below, the values are mixed up where my db value goes to my table id.
window.location.assign("test.php?db=&tbl=" + yourDB);
I tried putting both IDs only in my new page and using reload as my DB value would already have been passed. Using
window.location.reload("test.php?db=&tbl=" + yourTbl);
But this doesnt work either.
How can I get the url to have both my DB and table in the correct format? Like
test.php?db=test&tbl=customer
EDIT
yourDB variable is passed from a select form option from a different page which in turn opens the new page where the yourTbl variable exists.I can't therefore call yourDb
window.location = 'test.php?db=' + yourDB + '&tbl=' + yourTbl ;
'OP is asking: yourDB since this variable stores the values of select options from a different page.Any ideas'
My answer is 'Get value from selection menu list in the another page, and save this value into local storage or session storage.'
Something like this,
// save your db
window.sessionStorage.setItem("db", yourDB)
// get your db
var obj = window.sessionStorage.getItem("db");

how to remove session variables/stotage in html page

I am setting and getting session variables in my html pages loke below
sessionStorage.setItem('AbnormalLogout', AbnormalLogout);
var AbnormalLogout= sessionStorage.getItem("AbnormalLogout");
but when i use
sessionStorage.removeItem('AbnormalLogout');
i can get this session variable using getitem property on another page after redirecting
Try:
this will completely clear localStorage
localStorage.clear();
this will completely clear sessionStorage
sessionStorage.clear();
Try this also:
Object.keys(sessionStorage).forEach(function(item) {
sessionStorage.removeItem(item);
});

I want to save user preferences on a javascript code

I have this javascript code that changes the style of the website. but this code changes the style only when you click on it. and after you refresh the page it returns to default. I want it to save the users prefrences. I really like the code and I do not want to change it with another one. can you please help.
<script type="text/javascript">
$(document).ready(function() {
$("#fullswitch").click(function() {
$("#chpheader").removeClass("compact");
$("#imgg").removeClass("compact");
$("#chpheader").removeClass("original");
$("#imgg").removeClass("original");
$("#chpheader").addClass("normal");
$("#imgg").addClass("normal");
});
$("#compactswitch").click(function() {
$("#chpheader").addClass("compact");
$("#imgg").addClass("compact");
$("#chpheader").removeClass("original");
$("#imgg").removeClass("original");
$("#chpheader").removeClass("normal");
$("#imgg").removeClass("normal");
});
$("#originalswitch").click(function() {
$("#chpheader").addClass("original");
$("#imgg").addClass("original");
$("#chpheader").removeClass("compact");
$("#imgg").removeClass("compact");
$("#chpheader").removeClass("normal");
$("#imgg").removeClass("normal");
});
});
</script>
<html>
<body>
<span id="t1">0</span>
<span id="t2">0</span>
<span id="t3">0</span>
<span id="t4">0</span>
<span id="t5">0</span>
<span id="t6">0</span>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("lastname", "Smith");
localStorage.setItem("first", "Smi");
// Retrieve
var c = document.getElementById("result").innerHTML = localStorage.getItem("lastname");
var b = document.getElementById("result").innerHTML = localStorage.getItem("first");
document.getElementById("t1").innerHTML = c;
document.getElementById("t2").innerHTML = b;
//localStorage.removeItem("lastname");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage....";
}
</script>
</body>
</html>
There is a jQuery cookie plugin there are examples on that page as well so you can see how you can set and read a value from the cookie.
Once the value is read it's just a simple matter of loading the right theme.
var theme = $.cookie('name_of_selected_theme');
setTheme(theme);
function setTheme(themeName){
if(themeName == "One"){
...
}else...
}
However cookies only allow for 4KB of data and are passed in every HTTP call. A better idea many be localStorage. You can use YUI Storage Lite library which is < 3KB in size and you can easily use it to save data in browser localStorage and load from it. You can save at least 5MB of data using localStorage.
Example code from the link above:
YUI({
//Last Gallery Build of this module
gallery: 'gallery-2010.12.01-21-32'
}).use('gallery-storage-lite', function (Y) {
// For full compatibility with IE 6-7 and Safari 3.x, you should listen for
// the storage-lite:ready event before making storage calls. If you're not
// targeting those browsers, you can safely ignore this step.
Y.StorageLite.on('storage-lite:ready', function () {
// To store an item, pass a key and a value (both strings) to setItem().
Y.StorageLite.setItem('kittens', 'fluffy and cute');
// If you set the optional third parameter to true, you can use any
// serializable object as the value and it will automatically be stored
// as a JSON string.
Y.StorageLite.setItem('pies', ['apple', 'pumpkin', 'pecan'], true);
// To retrieve an item, pass the key to getItem().
Y.StorageLite.getItem('kittens'); // => 'fluffy and cute'
// To retrieve and automatically parse a JSON value, set the optional
// second parameter to true.
Y.StorageLite.getItem('pies', true); // => ['apple', 'pumpkin', 'pecan']
// The length() method returns a count of how many items are currently
// stored.
Y.StorageLite.length(); // => 2
// To remove a single item, pass its key to removeItem().
Y.StorageLite.removeItem('kittens');
// To remove all items in storage, call clear().
Y.StorageLite.clear();
});
});
I suppose you have two options, store the info client side, or store the info server side.
If you actually have a "user" server side (the person has to log in, yada yada yada), you can store this setting for the user (add some data to where ever the user info is stored).
If you don't want it that persistent, you can store it in local storage (not very browser friendly) or cookies. You really have no guarantee that these settings will stay around, as they are controlled by the browser, users can have their browsers set to never save this info.
Either way (client or server) you can read the setting and set the classes server-side and skip the javascript for changing the classes. Always better to do it on the server.
You may use HTML5 window.localStorage to store user preferences and trigger the corresponding layout changes.
Or use cookies as previously suggested.
Take a look at this article: http://diveintohtml5.ep.io/storage.html
Use cookies to store the users options.
http://www.quirksmode.org/js/cookies.html
Use localStorage to store the user preferences, and on reload load the preferences back in.
Here's a good tutorial.
How to write:
localStorage['someKey'] = 5;
How to read: var lastKeyValue = localStorage['someKey'];
use session storage
//set in session storage
$("#block-menu-menu-organisation > ul > li > a" ).bind( "click", function(evt) {
//in that case one expanded at the time
sessionStorage.clear();
var par = $(evt.target).parent();
sessionStorage.setItem(par.attr('id'),par.attr('class'));
console.log(par.attr('class'));
});
// //retrieve class from session
if(typeof sessionStorage!='undefined') {
$('#block-menu-menu-organisation > ul > li' ).each(function(i) {
if( $(this).attr('id') in sessionStorage) {
$(this).attr('class', sessionStorage.getItem($(this).attr('id')));
}
});
}

Categories