How to write value in text file using Javascript - javascript

I'm working on a number of views per page using JavaScript.
<SCRIPT LANGUAGE="JavaScript">
<!--
var cookiec = document.cookie
if (cookiec != "") {
var eqchr = 0;
for (var cloop = 1; cloop <= cookiec.length; cloop++) {
if (cookiec.charAt(cloop) == "=") {
eqchr=(++cloop);
}
}
var cookiess = 0;
clength=cookiec.length;
cookies="";
for (cloop = eqchr; cloop < clength; cloop++) {
if (cookiec==";") {
cloop=clength;
}
else {
cookies = cookies + cookiec.charAt(cloop);
}
}
cookiess = parseInt(cookies);
document.write("[" + cookiess + "]");
cookiess++;
cookies = cookiess;
var one_week = 7 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime(expDate.getTime() + one_week);
document.cookie = "Counter=" + escape(cookies) + "; expires=" + expDate.toGMTString();
}
else {
var one_week = 7 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime(expDate.getTime() + one_week);
document.cookie = "Counter=2; expires=" + expDate.toGMTString();
document.write("[1]");
}
// -->
</SCRIPT>
I am using the above JavaScript to calculate the number of views per page and I want to write the data in a text file.
Do you have any suggestions?

If your JavaScript is running in a browser environment, I would highly recommend either using HTML5 localStorage for storing (key, value) pairs or using AJAX to communicate with a server instead of trying to access a file on the client machine which may potentially become a security/privacy issue. Below is a simple example of using localStorage to store a page view count:
if (localStorage.numberOfViews) {
localStorage.numberOfViews = Number(localStorage.numberOfViews) + 1;
} else {
localStorage.numberOfViews = 1;
}
Hope this helps!

Javascript, running in a normal web browser, has very very limited access to the local file system.
So modern web browsers will let you save data to a file in a specialized directory, isolated from everything else.
For the most part, using localStorage (as mentioned by the others), is your best bet.
If you are running under Windows you can create a specialized file called an '.HTA' which runs with the same kind of access and permissions that regular files use.

Attribute LANGUAGE="JavaScript" is deprecated. You can remove it.
Now, replying your question, you can do it with PHP. Send the data when the user enter the page, send it via AJAX to your server and proccess it with PHP.

Related

use saved variable in cookie with php

For last two weeks I was working on saving a page id in cookies and then retrieve it in some other page.
Finally I solved it but now I have some other problem I want to use this id (the one I saved in cookie and retrieve it) in my php code .
I know javascript is client side code and php is server side code but I have to do this. Please help me out with this.
This is my javascript code which is working great and I get the saved id with this line "+value.favoriteid+"
<script>
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
var faves = new Array();
$(function(){
var favID;
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
var favID = (pair[0]=='ID' ? pair[1] :1)
//alert(favID);
}
$(document.body).on('click','#addTofav',function(){
var fav = {'favoriteid':favID};
faves.push(fav);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
var myfaves = JSON.parse(readCookie('favespages'));
if(myfaves){
faves = myfaves;
} else {
faves = new Array();
}
$.each(myfaves,function(index,value){
var element = '<li class="'+index+'"><h4>'+value.favoriteid+'</h4> ';
$('#appendfavs').append(element);
});
});
</script>
Read cookie on php side it is easiest thing after you set them by js.
Any cookies sent to you from the client will automatically be included
into a $_COOKIE auto-global array if variables_order contains "C". If
you wish to assign multiple values to a single cookie, just add [] to
the cookie name.
Depending on register_globals, regular PHP variables can be created
from cookies
Here php are some examples:
<?php
echo $_COOKIE["your cookie name"];
?>
<?php
print_r($_COOKIE);
?>
It's not recommended to rely on them as this
feature is often turned off for the sake of security.
http://php.net/manual/en/features.cookies.php
If you already managed to save to cookie in javascript, then it should be no problem to retrive it in PHP, just use $_COOKIE["COKKIE_NAME"] (Where you ofcourse change COOKIE_NAME, to the name of the cookie you saved in JS)..
Have a look at http://php.net/manual/en/features.cookies.php for more examples.

How to save a static variable with Javascript even when refreshing page

In the following code, I would like to save chrono time even when i reload the page. The variable to save as static is "diff". Because i need my chrono to return me the las time saved when i redirect to the same page. this code is declared in the header section. This code is not doing so, how would I accomplish that?
`
<script language="JavaScript">enter code here
var startTime = 0
var start = 0
var end = 0
var diff = 0
var timerID = 0
function chrono(){
end = new Date()
diff = end - start
diff = new Date(diff)
var msec = diff.getMilliseconds()
var sec = diff.getSeconds()
var min = diff.getMinutes()
var hr = diff.getHours()-1
if (min < 10){
min = "0" + min
}
if (sec < 10){
sec = "0" + sec
}
if(msec < 10){
msec = "00" +msec
}
else if(msec < 100){
msec = "0" +msec
}
//alert(document.getElementById("chronotime").innerText);
/* document.getElementById("pps").innerHTML = hr + ":" + min + ":" + sec + ":" + msec
document.getElementById("ppa").innerHTML = hr + ":" + min + ":" + sec + ":" + msec */
document.getElementById("chronotime").innerHTML = hr + ":" + min + ":" + sec + ":" + msec
timerID = setTimeout("chrono()", 10)
}
function chronoStart(){
start = new Date()
chrono()
}
function chronoContinue(){
start = new Date()-diff
start = new Date(start)
chrono()
}
function chronoReset(){
document.getElementById("chronotime").innerHTML = "0:00:00:000"
start = new Date()
}
function chronoStopReset(){
document.getElementById("chronotime").innerHTML = "0:00:00:000"
document.chronoForm.startstop.onclick = chronoStart
}
function chronoStop(){
document.chronoForm.startstop.value = "start!"
document.chronoForm.startstop.onclick = chronoContinue
document.chronoForm.reset.onclick = chronoStopReset
clearTimeout(timerID)
}
</script>
You can not keep a variable alive after refresh as variables are created in window which will get reloaded after refresh.
var a = 10;
//You can access this variable as below
console.log(a);//1st way
console.log(window.a);//2nd Way
So when the page gets refreshed, window gets reloaded.
Try to save your variables in the form of cookie(Old Traditional way)
document.cookie="key=value; key=value....."
Other options exists are:(Comparatively new.)
in browser "HTML5 Web SQL Database"(Reference).
But some time ago, I tested and it was not working on ff.
Local Storage. Below is the syntax:
localStorage.setItem("start", "10");
The options discussed above are for client side. The value can also be saved at server side.
Within the scope of a page, there is no way to have variables that survive page reloads. You could attempt browser storage, but that's risky (user may have multiple windows/tabs open with the same page, resulting in confusion).
The top option is to keep date information on the server in the user's session context (store timer start date when first request is received).
Having that in the user's session, you will be able to detect that the user's timer had already started upon subsequent calls.
This option also shields you from potential problems linked to multiple tabs (though not multiple/different browsers)
you can use browser's localStorage to achieve this action. As javascript does not work cross domain, either you should use localstorage or some back-end to achieve this functionality.
However when you use localStorage, the user can open up it's console and can use the command, localStorage.clear() to clear all browser's storage, so latter option is more reliable.
// Set value
localStorage.setItem(saveDiff, diff);
window.onload = function() {
//retrieve value back after page load
var saveDiff = localStorage.getItem(differenceValue);
}

Set a Javascript Cookie based on URL Params

I'm curious if someone can help a very new Javascript user make sense of how to set a cookie, based on specific URL parameters. I see that pulling the data from the URL using JavaScript is covered in this post:
How can I get query string values in JavaScript?
But I can not figure out how to pull that information into a cookie to store the information throughout a users session on the site.
I would like to grab 3 main URL parameters:
utm_source
utm_medium
utm_campaign
And then store them in a cookie in Google Tag Manager using Javascript.
I can not wrap my head around making this happen. Any help would be greatly appreciated. Sorry I dont have much code to show for reference, but I have been experimenting ( and failing ) for hours now.
Thank you so much for any insight on this.
Cheer,
Melissa
Edit:
Sorry...I wasn't expecting someone to write it for me, I just didn't think my very failed attempts would help anyone see what I was trying to do so I just explained.
Here is my code as of now, and I know it's sort of working. I'm editing a previous cookie that stores the site referrer in a cookie. So as it stands right now, the cookie stores the referrer on the first pageview, then if you go to a different page it will show the {{utm_medium}} and continue to show that throughout the visit. I would like for it to not show the referrer, but output a cookie that displays {{utm_source}} | {{utm_medium}} | {{utm_campaign}} if that's even possible...
Thank you again for any help or pointers or articles. I really appreciate it.
<script> //get referrer info and shorten it
var ref = {{Referrer}}
function extractDomain(url) {
var domain;
//find & remove protocol (http, ftp, etc.) and get domain
if (url.indexOf("://") > -1) {
domain = url.split('/')[2];
} else {
domain = url.split('/')[0];
}
//find & remove port number
domain = domain.split(':')[0];
return domain;
}
ref = extractDomain(ref);
//create cookie
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=/";
}
var cookie = "";
//check if UTMs are present and set cookie content to the source utm
if ({{utm_source}}) {
createCookie("utmsource", cookie + {{utm_source}}, 1000)
} else if ({{utm_medium}}) {
createCookie("utmsource", cookie + "Email", 1000)
//check if referrer is present and set cookie content to the referrer
} else if ({{utm_campaign}}) {
createCookie("utmsource", cookie + "{{utm_campaign}}", 1000)
} else if {
createCookie("utmsource", cookie + "Email", 1000)
};
</script>
When you use cookie + something, you're not updating the cookie string. So each time you do this, you're just concatenating with the original, empty value of this string. Instead of calling setcookie multiple times, update the cookie string as you test the different variables, then call setcookie at the end with the combined value.
You shouldn't use else if between each test, since that will only add the second variable to the cookie if the first variable didn't exist. But you want all the variables put into the cookie.
var cookie = "";
if ({{utm_source}}) {
cookie += {{utm_source}};
}
if ({{utm_medium}}) {
cookie += ' | ' + {{utm_medium}};
} else {
cookie += ' | Email';
}
if ({{utm_campaign}}) {
cookie += ' | ' + {{utm_campaign}};
} else {
cookie += ' | Email';
}
setcookie('utm_source', cookie, 1000);

Why does jQuery cookie not actually set a cookie?

I am developing an application using jQuery that uses cookies. Right now, it is located at application.html on my PC desktop.
However, I cannot store and retrieve a cookie. I had included jquery-1.7.1.min.js, json2.js, and jquery.cookie.js in my HTML file in that order.
Here is how I am storing a cookie to last for 7 days:
$.cookie("people", JSON.stringify(people_obj_array), {expires: 7});
The global array people_obj_array looks like
[
{
"name": "Adam",
"age": 1,
},
{
"name": "Bob",
"age": 2,
},
{
"name": "Cathy",
"age": 3,
},
]
When I test JSON encryption with alert(JSON.stringify(people_obj_array)), it looks fine:
However, when I retrieve this cookie via:
alert($.cookie("people"));
before even refreshing the page, an alert pops up that reads "null." Shouldn't the text be the alert JSON string? Am I using the JQuery cookies library correctly?
Just to clarify, here is how I am testing:
$.cookie("people", JSON.stringify(people_obj_array), {expires: 7}); // store
alert($.cookie("people")); // attempt to retrieve
I have Firebug, and I am willing to do some Console tests.
It's probably the fact the file is on your desktop that's causing the problem. Browsers normally behave by serving up cookies based on the domain they were received from and their path.
You may not be able to read the cookie immediately after setting it: Writing a cookie involves setting headers in a HTTP request and, likewise, reading them involves reading headers in a HTTP response.
Try hosting your page on a web-server and see if that works for you.
If you are having troubles with the cookies plugin why not just make up your own cookie functions? Read, Write and (optional) delete.
var createCookie = function(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=/';
};
var readCookie = function(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;
};
var eraseCookie = function(name) {
createCookie(name, '', -1);
};
I cannot comment on the specific plugin as I have never used it.. however these functions all work and have been tested.
So for your example:
createCookie("people", JSON.stringify(people_obj_array), 7); // store
alert(readCookie("people")); // retrieve
eraseCookie("people"); // remove
alert(readCookie("people")); // oo look i'm no longer here.
From my research jquery.cookie.js is fairly old, and doesn't seem to be maintained any longer. You might have better luck using this library instead. Its description on Google Code is "Javascript Cookie Library with jQuery bindings and JSON support", and includes methods for everything you're trying to do!

HTML5 Local Storage fallback solutions [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I'm looking for javascript libraries and code that can simulate localStorage on browsers that do not have native support.
Basically, I'd like to code my site using localStorage to store data and know that it will still work on browsers that don't natively support it. This would mean a library would detect if window.localStorage exists and use it if it does. If it doesn't exist, then it would create some sort of fallback method of local storage, by creating its own implementation in the window.localStorage namespace.
So far, I've found these solutions:
Simple sessionStorage implementation.
An implementation that uses cookies (not thrilled with this idea).
Dojo's dojox.storage, but it is it's own thing, not really a fallback.
I understand that Flash and Silverlight can be used for local storage as well, but haven't found anything on using them as a fallback for standard HTML5 localStorage. Perhaps Google Gears has this capability too?
Please share any related libraries, resources, or code snippets that you've found! I'd be especially interested in pure javascript or jquery-based solutions, but am guessing that is unlikely.
Pure JS based simple localStorage polyfill:
Demo: http://jsfiddle.net/aamir/S4X35/
HTML:
set key: foo, with value: bar<br/>
get key: foo<br/>
delete key: foo​
JS:
window.store = {
localStoreSupport: function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
},
set: function(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 = "";
}
if( this.localStoreSupport() ) {
localStorage.setItem(name, value);
}
else {
document.cookie = name+"="+value+expires+"; path=/";
}
},
get: function(name) {
if( this.localStoreSupport() ) {
var ret = localStorage.getItem(name);
//console.log(typeof ret);
switch (ret) {
case 'true':
return true;
case 'false':
return false;
default:
return ret;
}
}
else {
// cookie fallback
/*
* after adding a cookie like
* >> document.cookie = "bar=test; expires=Thu, 14 Jun 2018 13:05:38 GMT; path=/"
* the value of document.cookie may look like
* >> "foo=value; bar=test"
*/
var nameEQ = name + "="; // what we are looking for
var ca = document.cookie.split(';'); // split into separate cookies
for(var i=0;i < ca.length;i++) {
var c = ca[i]; // the current cookie
while (c.charAt(0)==' ') c = c.substring(1,c.length); // remove leading spaces
if (c.indexOf(nameEQ) == 0) { // if it is the searched cookie
var ret = c.substring(nameEQ.length,c.length);
// making "true" and "false" a boolean again.
switch (ret) {
case 'true':
return true;
case 'false':
return false;
default:
return ret;
}
}
}
return null; // no cookie found
}
},
del: function(name) {
if( this.localStoreSupport() ) {
localStorage.removeItem(name);
}
else {
this.set(name,"",-1);
}
}
}​
I use PersistJS (github repository), which handles client-side storage seamlessly and transparently to your code. You use a single API and get support for the following backends:
flash: Flash 8 persistent storage.
gears: Google Gears-based persistent storage.
localstorage: HTML5 draft storage.
whatwg_db: HTML5 draft database storage.
globalstorage: HTML5 draft storage (old spec).
ie: Internet Explorer userdata behaviors.
cookie: Cookie-based persistent storage.
Any of those can be disabled—if, for example, you don't want to use cookies. With this library, you'll get native client-side storage support in IE 5.5+, Firefox 2.0+, Safari 3.1+, and Chrome; and plugin-assisted support if the browser has Flash or Gears. If you enable cookies, it will work in everything (but will be limited to 4 kB).
have you seen the polyfill page on the Modernizr wiki?
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills
look for the webstorage section on that page and you will see 10 potential solutions (as of July 2011).
good luck!
Mark
Below is a tidied up version of Aamir Afridi's response that keeps all its code encapsulated within the local scope.
I've removed references that create a global ret variable and also removed the parsing of stored "true" and "false" strings into boolean values within the BrowserStorage.get() method, which could cause issues if one is trying to in fact store the strings "true" or "false".
Since the local storage API only supports string values, one could still store/retrieve JavaScript variable data along with their appropriate data types by encoding said data into a JSON string, which can then be decoded using a JSON encode/decode library such as https://github.com/douglascrockford/JSON-js
var BrowserStorage = (function() {
/**
* Whether the current browser supports local storage as a way of storing data
* #var {Boolean}
*/
var _hasLocalStorageSupport = (function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
})();
/**
* #param {String} name The name of the property to read from this document's cookies
* #return {?String} The specified cookie property's value (or null if it has not been set)
*/
var _readCookie = function(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;
};
/**
* #param {String} name The name of the property to set by writing to a cookie
* #param {String} value The value to use when setting the specified property
* #param {int} [days] The number of days until the storage of this item expires
*/
var _writeCookie = function(name, value, days) {
var expiration = (function() {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
return "; expires=" + date.toGMTString();
}
else {
return "";
}
})();
document.cookie = name + "=" + value + expiration + "; path=/";
};
return {
/**
* #param {String} name The name of the property to set
* #param {String} value The value to use when setting the specified property
* #param {int} [days] The number of days until the storage of this item expires (if storage of the provided item must fallback to using cookies)
*/
set: function(name, value, days) {
_hasLocalStorageSupport
? localStorage.setItem(name, value)
: _writeCookie(name, value, days);
},
/**
* #param {String} name The name of the value to retrieve
* #return {?String} The value of the
*/
get: function(name) {
return _hasLocalStorageSupport
? localStorage.getItem(name)
: _readCookie(name);
},
/**
* #param {String} name The name of the value to delete/remove from storage
*/
remove: function(name) {
_hasLocalStorageSupport
? localStorage.removeItem(name)
: this.set(name, "", -1);
}
};
})();
I personally prefer amplify.js. It has worked really well for me in the past and I recommended it for all local storage needs.
supports IE 5+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ and provides a consistent API to handle storage cross-browser
store.js uses userData and IE and localStorage on other browsers.
It does not try to do anything too complex
No cookies, no flash, no jQuery needed.
Clean API.
5 kb compressed
https://github.com/marcuswestin/store.js
The MDN page for DOM storage gives several workarounds that use cookies.
Lawnchair seems to be a good alternative too
a lawnchair is sorta like a couch except smaller and outside. perfect
for html5 mobile apps that need a lightweight, adaptive, simple and
elegant persistence solution.
collections. a lawnchair instance is really just an array of objects.
adaptive persistence. the underlying store is abstracted behind a consistent interface.
pluggable collection behavior. sometimes we need collection helpers but not always.
There is realstorage, which uses Gears as a fallback.

Categories