How can I save a cookie - javascript

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!

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);

Sending data and saving in a text field

I have a main page with a popup window.
<textarea class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
There is also a second page. (/conclusion/main)
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
I enter the text in the window and send. The window should close and the text should be sent to the second page and the text should be saved in the field "textarea". Even if they close the page or reload, the text should remain in the second page.
This code allows you to save, but after closing the page, does not save
(function(){
var textarea = document.getElementById('retro');
if (localStorage.retro)
{
textarea.value = localStorage.retro;
}
textarea.onchange = function()
{
localStorage.retro = this.value;
}
})();
Sends from the first page to the second
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params2;
}
params = getParams();
name = unescape(params["name"]);
document.getElementById('retro').innerHTML = name;
There are some questions around what you are trying to do here. What I have done is broken this down into 2 parts
Passing the local storage between 2 pages and accessing it.
Decoding Parameters in the URL and assigning them
Some assumptions that I made:
I have noticed some of the classes from bootstrap so i assume that you have jQuery on the page and also you may know how to use it.
Using chrome for testing this
PART 1 - Passing localstorage between windows:
First thing to note is you may be better using a cookie library (js-cookie) or creating one yourself that you can access. As localstorage may well be insecure depending on what data you want to store in there.
With that out of the way, you were on the right track, just needed to add your event listener to 'input' as i think then every keystroke the data in local storage is being updated.
Page 1
HTML
<textarea id="retro" class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
JS (I would recommend place this at the bottom of you page for quick testing)
<script type="text/javascript">
var textarea = document.getElementById('retro');
textarea.addEventListener('input',function(){
localStorage.setItem('retro', this.value);
})
</script>
In Chrome developer tools if you watch the variable 'localstorage' then you will see this change as you key in the value.
What I have done here is bound the event listener to the text area so that any 'input' the value changes, furthermore is am setting the item in the localstorage
PAGE 2
HTML
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
JS
<script type="text/javascript">
var textarea = document.getElementById('retro').value = localStorage.getItem('retro');
</script>
Here using the 'getItem' method for localstorage you can then retrieve it from the storage area and output it as the value of the textarea.
Obviously is the cache or localstorage is cleared then this value will disappear.
PART 2 - Decoding Parameters in the URL and assigning them
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
This function above will get you any parameter you want form the url I found this from here. This is using jQuery.
Here is how you would use it
// example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
Well I hope this answers your question on both parts, and helps you further, please add any comments if I have missed anything and I will be happy to update my answer

Chrome redirection (SP modal newform window)

i'm using JavaScript to make some small customization in default SharePoint 2013 issue tracker. When user submit an issue (default SharePoint function presave) JavaScript should redirect document to new URL. Everything works fine in Firefox in IE but from unknown reason redirection doesn't work in Chrome.
I'm used location, replace.href, assign etc - result the same - chrome just save the form without redirection. Can you give me any hint why it doesn't work?
I'm using SP 2013 online (and i don't have access to SP designer)
<script src="/sites/SiteAssets/Scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/sites/SiteAssets/Scripts/sessvars.js"></script>
<script language="javascript" type="text/javascript" src="/sites/_layouts/15/clientpeoplepicker.js"></script>
<script type="text/javascript">
// Here i have small function to get email from sharepoint peoplePicker field
function getEmailFromPeoplePicker(title) {
var ppDiv = $("div[title='" + title + "']")[0];
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv.id];
var userList = peoplePicker.GetAllUserInfo();
var userInfo = userList[0];
var userEmail;
if(userInfo != null)
{
userEmail = userInfo.EntityData.Email;
}
return userEmail;
}
function PreSaveAction(){
// check if there is attachment
if ($('#onetidIOFile').get(0).files.length === 0) {
} else {
OkAttach() //attach file to form
}
//get email from field
var RequestApprover = getEmailFromPeoplePicker('Assigned To');
//create link for redirection with email at the end (ill use it latter for sending emails)
var targetUrl = '/sites/SitePages/RedirectDestination.aspx' + '#' + RequestAprover;
//window.location.href = targetUrl;
//location.replace(targetUrl);
//window.location.assign(targetUrl);
// window.top.location.href = targetUrl;
window.location.assign(targetUrl); // <---------- redirection which works in IE and FireFox but not in Chrome
//window.location.href = targetUrl;
//window.location.assign(targetUrl);
//window.parent.location.href(targetUrl);
//setTimeout(function(){location.href = targetUrl},500);
return true;
}
</script>
I believe you should have "return false;" (instead of return true;) at the end of your PreSaveAction function implementation. Looks like in Chrome redirect takes more time then in other browsers, so Sharepoint continues usual form flow (e.g. continues to PreSaveItem etc.)

How to make webpage that remembers the choices made via javascript change attributes?

Hello , This is the code that can change the image src and I am using it offline .It has 2 button , one of which turns on the light and other turns off it. It works well! But problem is it doesn't remember the choice i made once i reload the page. Ex. If i turn on the light , it shows the glowing bulb but forgets after reload.
Note: I have tried some online solutions but since it was about something related to javascript, it didn't seem to work.
Target is chrome only!
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attributes.</p>
<p>In this case JavaScript changes the src (source) attribute of an image.
</p>
<button
onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on
the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button
onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off
the light</button>
</body>
</html>
As already noted you can use localStorage to store the src and load it next page load. To use this for your example you could use the following code:-
Html
<button id="btn1">Turn on the light</button>
<img id="myImage" src="off.png">
<button id="btn2">Turn off the light</button>
JS
//set src on page load
if(localStorage.imgSrc) {
document.getElementById('myImage').src = localStorage.imgSrc;
}
//set src and localStorage on click
document.getElementById('btn1').onclick = function() {
localStorage.imgSrc = document.getElementById('myImage').src = 'on.png';
}
document.getElementById('btn2').onclick = function() {
localStorage.imgSrc = document.getElementById('myImage').src = 'off.png';
}
You can use either localstorage that is being supported by the most modern browsers or use cookie.
What i would do is to check in a function if localstorage is being supported if not use cookie like this
function localStorageExists(){
try {
localStorage.setItem(simpleTest, simpleTest);
localStorage.removeItem(simpleTest);
return true;
} catch(e) {
return false;
}
}
function saveOption(value) {
if(localStorageExists() === true){
// available use local storage
localStorage.setItem(option, value);
}else{
// unavailable use cookie
createCookie("option", value, 30);
}
}
function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
you can also have a function that detects and reads accordingly ;)

how to transfer values between html pages?

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 ).

Categories