I'm writing a simple diary application and I'd like the user to input the entry on one page and have some js script take that entry and collect it into a different page ("diary-posts"). With the code below I can only collect posts within the same page however:
<! DOCTYPE html>
<html lang="en">
<body>
<header class="text-center">
<h2>
Diary Posts
</h2>
</header>
<div class="wrapper text-center">
<textarea id="txt" rows="3" placeholder="How's your day?"></textarea>
<div class="text-l">
<button onclick="getRs()">Create</button>
</div>
<div id="rs" class="wrapper"></div>
<script src="diary-script.js"></script>
</body>
</html>
function _(id){
return document.getElementById(id)
}
function getRs() {
let txt = _('txt').value
const d = new Date()
_('rs').innerHTML += `<div class="card"><p>${txt}</p>
<small>${d.toLocaleTimeString()}, ${d.toLocaleDateString()}</small></div>`
}
How can I modify this in a simple way to achieve what I want?
There is a lot of ways but I recommend you these options. Choose the best one that works for you.
1. Cookie
This option is best if you want it to use in backend too, because you send cookies data to the backend by every requests. so the data must NOT be too large and must be needed in the backend. otherwise you should use the "localStorage".
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
let expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
setCookie("name", value, 1) //set the cookie for 1 day
getCookie("name") //get the cookie everywhere you want
2. localStorage
If you want to use it only in the user device, this is the option you wanna pick.
note: localStorage stores the data with no expiration date. the data will never ever will be deleted automatically unless you delete it or the user delete it by browser settings.
localStorage.setItem("fieldName", data); //set the item
localStorage.getItem("fieldName"); //get the item
3. sessionStorage (recommended)
sessionStorage is similar to localStorage but the difference is that this will be deleted when user close the browser. so if the data is not so much important and you don't need it next time the user visits the page, this option is made for you.
sessionStorage.setItem("fieldName", data); //set the data
sessionStorage.getItem("fieldName"); // get the data
4. Use backend
you can also store the data in database via backend. you can use an API to send the data to the backend. this option is good for when you need the data in backend and you always need it.
Related
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!
After click on button in first.html, i have been called a function and updated labels in second.html, but i able to see a second.html not able to see the updated value in labels in second.html.Please help me how to achieve.
function updateLabels(){
$('#entryNumber').text("123");
$('#responsedate').text("23-9-2015");
window.location = 'second.html';
}
ex:second.html
<body>
<label>Entry Number:</label>
<label id="entryNumber" for="entryNumber"></label><br><br>
<label>Respond Date:</label>
<label id="responsedate" for="responsedate"></label><br><br>
<label>Response Text:</label>
</body>
You can achieve your goal in client side via.. 3 options
1. By Local Storage
On first page set your second page label value in local storage.
// In 1st page
function updateLabels(){
localStorage.setItem('Second_Page_LabelVal', "apple");
window.location = 'second.html';
}
On second Page get this value from local storage and set it to your labels value
// In 2ndPage
$( document ).ready(function() {
// Retrieve the object from storage
var retrievedVal = localStorage.getItem('Second_Page_LabelVal');
$("2ndpagelabelId").text(retrievedVal);
});
2. By cookie
On first page set your second page label value in COOKIES.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
// In 1st page
function updateLabels(){
createCookie(('Second_Page_LabelVal', "apple",1);
window.location = 'second.html';
}
On second Page get this value FROM COOKIE and set it to your labels value
// In 2ndPage
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return
c.substring(nameEQ.length,c.length);
}
return null;
}
$( document ).ready(function() {
// Retrieve the object from cookie
var retrievedVal = readCookie('Second_Page_LabelVal');
$("2ndpagelabelId").text(retrievedVal);
});
3. By querystring Url
Redirect page with second page value in query string
// In 1st page
function updateLabels(){
window.location = 'second.html?SecondpageValue=value1';
}
Get the value from url and set it to label.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" :
decodeURIComponent(results[1].replace(/\+/g, " "));
}
$( document ).ready(function() {
// Retrieve the object from url
var retrievedVal = getParameterByName('SecondpageValue');
$("2ndpagelabelId").text(retrievedVal);
});
Html page DOES NOT save your status, and we needs a server-side program to handle usually.
In your case, maybe a modal dialog is useful.
Try using $.get() , substitute .replaceWith() for window.location at same document
function updateLabels(html){
$(html).find("#entryNumber").text("123");
$(html).find("#responsedate").text("23-9-2015");
$("body").replaceWith(html);
}
$.get("second.html", updateLabels);
I'm working on a page that refreshes itself every 5 minutes
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true" />
On the page is a JS script that should run the first two times the page reloads. When the page reload's for the third time, the script should not execute.
So far, I've created a cookie and given it an initial value of 0, for every refresh I increment it's value (rewrite the cookie) and if the value is smaller than 3 i execute the part of a script. The things is that if I close the tab and reopen the page in another tab, the cookie has the incremented value, and I want it to always start from 0.
Here's what i've done so far:
var value = 0;
$(document).ready(function() {
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie() {
var cookieValue = getCookie('siteRefreshCookie');
if (cookieValue !== '') {
var newValue = parseInt(getCookie('siteRefreshCookie')) + 1;
if (newValue < 3) {
//script to be executed
document.cookie = "siteRefreshCookie="+ newValue +";";
}
} else {
document.cookie = "siteRefreshCookie="+ value +";";
}
}
checkCookie();
})
Could I suggest using a query string instead?
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true&count=1" />
Then as an ASP programmer myself I would do something like:
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true&count=<%=CInt(0 & Request.Querystring("count")) + 1%>" />
But you can probably achieve this using PHP, or even JS I imagine if you have no back-end language suitable.
The problem with using cookies is that they are tied to that website, rather than that window. Even if you reset the cookie with an unload function like Pete suggested, you'll then run into problems like if for example you have two tabs open with the same page.
I have a newsletter sign up form that I would like to load (popup) only one time every 15 days, otherwise it might get a bit annoying. I am currently using this jquery code to load the popup form when the page loads.
<div id="test-popup" class="white-popup mfp-hide">
Popup Form
</div>
<script>
jQuery(window).load(function(){
jQuery.magnificPopup.open({
items: {src: '#test-popup'},type: 'inline'}, 0);
});
</script>
This works fine when loading the form every time you access the page but I would like to limit this so new users see it once every 15 days. Not sure if the 15 days is best practice just something I came up with?
You can use localStorage to do this.
$(window).on('load', function() {
var now, lastDatePopupShowed;
now = new Date();
if (localStorage.getItem('lastDatePopupShowed') !== null) {
lastDatePopupShowed = new Date(parseInt(localStorage.getItem('lastDatePopupShowed')));
}
if (((now - lastDatePopupShowed) >= (15 * 86400000)) || !lastDatePopupShowed) {
$.magnificPopup.open({
items: { src: '#test-popup' },
type: 'inline'
}, 0);
localStorage.setItem('lastDatePopupShowed', now);
}
});
<div id="test-popup" class="white-popup mfp-hide">
Popup Form
</div>
You can see a working example here: http://codepen.io/caio/pen/Qwxarw
functions for create and read cookies:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
create a cookie for 15 days:
createCookie('run_popup',true,15);
check for elapsed 15 days
if(!readCookie('run_popup'))
... code for run popup...
To make your popup open every 15 days for user you probably want to set a cookie that expires every 15 days. On your page, check if cookie has expired, if yes, show your form and reset your cookie.
In this thread you can find material for quick start with cookies.
That will work per browser per computer, ie if user opens your page in other browser, it will load your popup again.
I'm trying to set multiple cookies in document.cookie, but unfortunately only one is getting added.
I know there are multiple examples present on the 'Net for setting up these kind of cookies,and I followed one of them. But still I'm unable to set that out.
I followed this link to set my cookie.
My Code:
function setCookie(start_time,end_session_time,total_time,flag,count){
var cookie_string = "start_time="+start_time;;
if(end_session_time) {
cookie_string +="; end_session_time="+end_session_time;
}
if(total_time){
cookie_string +="; total_time="+total_time;
}
if(flag){
cookie_string +="; flag="+flag;
}
if(count){
cookie_string +="; count="+count;
}
document.cookie =cookie_string ;
console.log(cookie_string);
console.log("document.cookie ="+ document.cookie);
}
The Output:
cookie_string :: start_time=1369926508266; flag=1; count=1
document.cookie =start_time=1369926508266;
Adding a cookie is performed via document.cookie = "name=value"
to add multiple keys, you should perform multiple assigments
function setCookie(start_time, end_session_time, total_time, flag, count) {
document.cookie = "start_time=" + start_time;
if (end_session_time) {
document.cookie = "end_session_time=" + end_session_time;
}
if (total_time) {
document.cookie = "total_time=" + total_time;
}
if (flag) {
document.cookie = "flag=" + flag;
}
if (count) {
document.cookie = "count=" + count;
}
console.log("document.cookie = " + document.cookie);
}
Cookies are key value pairs (with some optional additional info added on, like the expiry date). To set more than one, you just set document.cookie more than once. The ; separator is used to specify the additional info, not to add more different cookies.
There you go a sample example to add, list and delete multiple cookies
<!DOCTYPE html>
<html>
<head>
<script>
var n=1;
function addCookie(){
document.cookie=n+"="+n;n++;
}
function ListCookies(){
var result = document.cookie;
document.getElementById("p").innerHTML=result;
}
function removeCookies(){
//document.cookie="";
var result = document.cookie;
var cookieArray = result.split(";");
for(var i=0;i<cookieArray.length;i++){
var keyValArr = cookieArray[i].split("=");
document.cookie=keyValArr[0]+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
}
</script>
</head>
<body>
<button onclick='addCookie()'>ADD COOKIE</button><br>
<button onclick='ListCookies()'>LIST COOKIES</button>
<button onclick='removeCookies()'>REMOVE COOKIES</button>
<h1>RESULT:</h1>
<p id="p"></p>
</body>
</html>