This script creates a cookie depending on form data, (ex: ?docname=My Document)
<script type="text/javascript">
{
var docname = getValue("docname"); // these go off another script to get form data
var save = getValue("save");
var url = window.location.href;
}
function setCookie(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 saveDoc() {
if (docname != '') {
setCookie(docname,url,730);
}
else {
// Nothing else to do
}
}
// Helps to find errors if they exist
window.onerror = function(errorMessage, url, line) {
var errorText = 'message: ' + errorMessage + '\nurl: ' + url + '\nline: ' + line + ' please contact us, and report this error.';
alert(errorText);
}
</script>
It creates the cookie and sets the name of it as the docname variable, but when it sets the url as the value, it cuts off the form data.
I've researched and changed the code but couldn't find an answer, can anyone help?
Solution
<script type="text/javascript">
{
var docname = getValue("docname"); // these go off another script to get form data
var save = getValue("save");
var url = window.location.href;
var recode = encodeURIComponent(url);
}
function setCookie(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 saveDoc() {
if (docname != '') {
setCookie(docname,recode,730);
}
else {
// Nothing else to do
}
}
// Helps to find errors if they exist
window.onerror = function(errorMessage, url, line) {
var errorText = 'message: ' + errorMessage + '\nurl: ' + url + '\nline: ' + line + ' please contact us, and report this error.';
alert(errorText);
}
</script>
changed the variable used to set the value to recode and set recode equal to encodeURIComponent(url); so it decodes the url, decoding it and making it possible to have form data in a value or name of a cookie, etc. Thanks to #epascarello
encodeURIComponent() is your friend here
document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";
and when you get it, you need to decode it with decodeURIComponent().
Related
Im trying to create my own analytics script for my website, and for this I have tried to put together a way to create userID and sessionID.
But I am not sure if I have done it correctly.
I'm trying to:
Check to see if user has set a userID - if not set it.
check to see if user has a sessionID - it not set it.
the userID is set to follow the user, where the user continues to hold the userID on several visits, where the sessionID is unique for each visit.
if (getCookie('yb_uid') != null) {
if (getCookie('yb_sid') != null) {
setCookie('yb_uid', getCookie('yb_uid'), 730);
setSessionCookie(getCookie('yb_sid'));
} else {
setCookie('yb_uid', getCookie('yb_uid'), 730);
setSessionCookie(setSID());
}
} else {
setCookie('yb_uid', setUID(), 730);
setSessionCookie(setSID());
}
if (getCookie('yb_sid') == null || getCookie('yb_sid') ==
'undefined' || !getCookie('yb_sid')) {
setSessionCookie(setSID());
}
function setUID() {
return "ybID#" + _setID(5) + "-" + _setID(5) + "-" + Date.now();
}
function setSessionCookie(value) {
var now = new Date();
var minutes = 30;
now.setTime(now.getTime() + (minutes * 60 * 1000));
document.cookie = "yb_sid=" + value + "; max-age=" + now.toUTCString() + "; expires=" + now.toUTCString() + "; path=/";
} /*set session cookie*/
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
} /* get cookie value */
function _setID(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
function setSID() {
var ts = Math.round(+new Date() + Math.random() / 1000);
return ts;
}
function setCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
var expires = "; max-age=" + date.toGMTString() + " expires=" + date.toGMTString();
} else {
var expires = "";
}
document.cookie = name + "=" + value + expires + ";path=/";
Maybe this has an even easier way to script it?
Have you tried UUID https://www.npmjs.com/package/uuid for generating an user id?
I am trying to create a button that creates a new cookie with an increased numeric value as it's name and a different value (which comes from a variable), each time it is clicked. But, I can't get it to work.
This is what I have:
var date = new Date()
date.setTime(date.getTime() + 7*24*60*60*1000);
var num=1;
function addCookie() {
var expString = "; expires=" + date.toGMTString();
var cookievalue=escape(document.button.addpart.value) + ";";
document.cookie=num + "=" + cookievalue + expString + "; path=/my-quote/";
num++;
}
Then the html is:
<button name="addpart"; value="<?php $pn ?>"; onclick='addCookie()'>ADD</button>
I started with the following code (which worked, but just created a new cookie with the name 1 and value 1, then 2 and 2, 3 and 3 etc. I adapted it, so I think that's where I have gone wrong or missed something:
var num=1;
function addCookie() {
document.cookie=num+"="+num;
num++;
}
Updated code
var date = new Date() date.setTime(date.getTime() + 7 * 24 * 60 * 60 * 1000);
var num = 1;
function addCookie() {
var expString = "; expires=" + date.toGMTString();
var cookievalue = escape(document.querySelector("[name=addpart]").value) + ";";
document.cookie = num + "=" + cookievalue + expString + "; path=/my-quote/";
}
I have made a Formula with on onchange="this.form.submit()" and a automatic page refresh function with window.location.replace();. My Problem is, that i need to know where the user clicked in the last time. My Solution was a second onclick="" event to get the id of the selected field. This works fine if i make no changes in the form. When i change some values and go to a other field, the onclick function didn't work.
How can i solve this problem? And by the way, sorry for my bad english.
<input name="'.$idname.'" value="'.$cont_field.'" type="text" class="loginField" size="'.$breite.'" style="width:98%;" id="'.$idname.'" onchange="this.form.submit()" onclick="focusCookie(event)">
<script type="text/javascript">
function focusCookie (event) {
event = event || window.event;
var target = event.target || event.srcElement;
var anch = target.id;
createCookie("anchor", anch, new Date(new Date().getTime() + 10000));
}
function createCookie(name, value, expires, path, domain) {
var cookie = name + "=" + escape(value) + ";";
if (expires) {
if(expires instanceof Date) {
if (isNaN(expires.getTime()))
expires = new Date();
}
else
expires = new Date(new Date().getTime() + parseInt(expires) * 1000 * 60 * 60 * 24);
cookie += "expires=" + expires.toGMTString() + ";";
}
if (path)
cookie += "path=" + path + ";";
if (domain)
cookie += "domain=" + domain + ";";
document.cookie = cookie;
}
</script>
And this ist the loadingfunction
//--> Loaders
function Loader($https_url,$seite,$loader_id){
$loaderurl = '<script type="text/javascript">window.location.replace("'.$https_url.'/index.php?inhalt=extranet&extra=formular&seite='.$seite.'#'.$loader_id).'");</script>';
return $loaderurl;
}
Ok 2 Problems solved and 1 still pending. I can send the form and catch the anchor tag befor. But after the Siteload the focus(); is lost...
Here my Code:
<script type="text/javascript">
function submitform (event) {
event = event || window.event;
var target = event.target || event.srcElement;
var anch = target.id;
createCookie("anchor", anch, new Date(new Date().getTime() + 10000));
sendeForm();
document.getElementById(anch).reload();
}
function createCookie(name, value, expires, path, domain) {
var cookie = name + "=" + escape(value) + ";";
if (expires) {
if(expires instanceof Date) {
if (isNaN(expires.getTime()))
expires = new Date();
}
else
expires = new Date(new Date().getTime() + parseInt(expires) * 1000 * 60 * 60 * 24);
cookie += "expires=" + expires.toGMTString() + ";";
}
if (path)
cookie += "path=" + path + ";";
if (domain)
cookie += "domain=" + domain + ";";
document.cookie = cookie;
}
function sendeForm(){
document.getElementById("ID").submit();
}
</script>
I solved it with a AJAX Form by sending the Data with a XMLHttpRequest. This works fine. The Variables are generated with PHP.
function ajax_post(){
//Vars
var xhr = new XMLHttpRequest();
var url = 'URL';
<?php echo $VARLIST; ?>
var ausgabe = <?php echo $VARS; ?>;
//Send
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var return_data = xhr.responseText;
document.getElementById("Register").innerHTML = return_data;
}
}
xhr.send(ausgabe);
document.getElementById("Register").innerHTML = "Reload..";
}
My problem seems to be easy but I can't make it work; I want to set a cookie variable called "splash" then display it (later I want use in IF clause)
Here is my code :
<html>
<head>
<script type="text/javascript">
document.cookie = "splash=" + encodeURIComponent("blue theme")
var re = new RegExp(splash + "=([^;]+)");
var value = re.exec(document.cookie);
alert(value);
</script>
</head>
<body>
</body>
</html>
You should change your regex to include splash as part of the quoted string. Even though spash is the variable you're using in the cookie, it does not automatically become a javascript variable.
document.cookie = "splash=" + encodeURIComponent("blue theme")
var re = new RegExp("splash=([^;]+)");
var theme = re.exec(document.cookie)[1];
re.exec returns an array. the first element is the entire matched string (including splash=). The second is your capture group (blue%20theme).
Use Following function to set and get 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 = "";
}
var fixedName = '';
name = fixedName + name;
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(name)
{
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
function eraseCookie(name)
{
createCookie(name, "", -1);
}
I am trying to save cookies in JavaScript and then display them on the page again but for some reason my setCookies function and displayCookies function is not working properly.. I want it to also expire after 1 week. It is coming from a form and when I put it in Web Developer in FireFox it says Reference Error setCookies and displayCookies is not defined. My jsfiddle is : http://jsfiddle.net/FmXJW/
function setCookies()
{
// this function will set cookies for each field in the reservation form, and set them to expire after one day
var Name = document.forms[0].txtName.value;
var Address = document.forms[0].txtAddress.value;
var City = document.forms[0].txtCity.value;
var State = document.forms[0].txtState.value;
var Zip = document.forms[0].txtZip.value;
var Email = document.forms[0].txtEmail.value;
var CarType = document.forms[0].txtCarType.value;
var PickupDate = document.forms[0].txtPickupDate.value;
var ReturnDate = document.forms[0].txtReturnDate.value;
var myDate = newDate();
myDate.setDate(myDate.getDate() + 7);
document.cookie = "name=" + encodeURIComponent(Name) + "; expires=" + myDate.toUTCString();
document.cookie = "address=" + encodeURIComponent(Address) + "; expires=" + myDate.toUTCString();
document.cookie = "city=" + encodeURIComponent(City) + "; expires=" + myDate.toUTCString();
document.cookie = "state=" + encodeURIComponent(State) + "; expires=" + myDate.toUTCString();
document.cookie = "zip=" + encodeURIComponent(Zip) + "; expires=" + myDate.toUTCString();
document.cookie = "email=" + encodeURIComponent(Email) + "; expires=" + myDate.toUTCString();
document.cookie = "carType=" + encodeURIComponent(CarType) + "; expires=" + myDate.toUTCString();
document.cookie = "pickupDate=" + encodeURIComponent(PickupDate) + "; expires=" + myDate.toUTCString();
document.cookie = "returnDate=" + encodeURIComponent(ReturnDate) + "; expires=" + myDate.toUTCString();
window.alert ("Your reservation has been saved.");
} // end function setCookies()
function displayCookies()
{
// this function will read the saved cookies, and repopulate the form with the cookie values
var cookieString = decodeURIComponent(document.cookie);
var cookieArray = cookieString.split("; ");
if (document.cookie == 0)
{
alert("You have not made a reservation");
}
else
{
// retrieve each cookie, and display the cookie value in the appropriate form field
document.forms[0].txtName.value = cookieArray[0].lastIndexOf("=") + 1);
document.forms[0].txtAddress.value = cookieArray[1].lastIndexOf("=") + 1);
document.forms[0].txtCity.value = cookieArray[2].lastIndexOf("=") + 1);
document.forms[0].txtState.value = cookieArray[3].lastIndexOf("=") + 1);
document.forms[0].txtZip.value = cookieArray[4].lastIndexOf("=") + 1);
document.forms[0].txtEmail.value = cookieArray[5].lastIndexOf("=") + 1);
document.forms[0].txtCarType.value = cookieArray[6].lastIndexOf("=") + 1);
document.forms[0].txtPickupDate.value = cookieArray[7].lastIndexOf("=") + 1);
document.forms[0].txtReturnDate.value = cookieArray[8].lastIndexOf("=") + 1);
}
} // end function displayCookies()
You have a couple of problems on your code:
You are not retrieving the value from the different fields stored on the cookie correctly, you need to use slice to get the right part.
I also guess the line var myDate = newDate(); should be var myDate = new Date();.
I have changed your fiddle (find it here) and loaded the code in <head> and now it seems to save and display the cookies correctly.