Create array in cookie with javascript - javascript

Is it possible to create a cookie using arrays?
I would like to store a[0]='peter', a['1']='esther', a['2']='john' in a cookie in JavaScript.

As you can read in this topic:
You combine the use jQuery.cookie plugin and JSON and solve your problem.
When you want to store an array, you create an array in JS and use JSON.stringify to transform it into an string and stored with $.cookie('name', 'array_string')
var myAry = [1, 2, 3];
$.cookie('name', JSON.stringify(myAry));
When you want to retrive the array inside the cookie, you use $.cookie('name') to retrive the cookie value and use JSON.parse to retrive the array from the string.
var storedAry = JSON.parse($.cookie('name'));
//storedAry -> [1, 2, 3]

Cookies can hold only strings. If you want to simulate an array you need to serialize it and deserialize it.
You could do this with a JSON library.

I add the code below Script (see the following code) into a javascript file called CookieMonster.js.
It's a wrapper around the current snippet from http://www.quirksmode.org/js/cookies.html
It works with arrays and strings, it will automagically escape your array/string's commas , and semi-colons ; (which are not handled in the original snippets).
I have listed the simple usage and some bonus usage I built into it.
Usage:
//set cookie with array, expires in 30 days
var newarray = ['s1', 's2', 's3', 's4', 's5', 's6', 's7'];
cookiemonster.set('series', newarray, 30);
var seriesarray = cookiemonster.get('series'); //returns array with the above numbers
//set cookie with string, expires in 30 days
cookiemonster.set('sample', 'sample, string;.', 30);
var messagestring = cookiemonster.get('sample'); //returns string with 'sample, string;.'
Bonuses:
//It also conveniently contains splice and append (works for string or array (single string add only)).
//append string
cookiemonster.append('sample', ' add this', 30); //sample cookie now reads 'sample, string;. add this'
//append array
cookiemonster.append('series', 's8', 30); //returns array with values ['s1', 's2', 's3', 's4', 's5', 's6', 's7', 's8']
//splice
cookiemonster.splice('series', 1, 2, 30); //returns array with values ['s1', 's4', 's5', 's6', 's7', 's8']
CookieMonster.js :
var cookiemonster = new Object();
cookiemonster.append = function (cookieName, item, expDays) {
item = cm_clean(item);
var cookievalue = cookiemonster.get(cookieName);
if (cookievalue instanceof Array) {
cookievalue[cookievalue.length] = item;
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
} else {
cm_createCookie(cookieName, cookievalue + item, expDays);
}
};
cookiemonster.splice = function (cookieName, index, numberToRemove, expDays) {
var cookievalue = cookiemonster.get(cookieName);
if (cookievalue instanceof Array) {
cookievalue.splice(index, numberToRemove);
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
}
};
cookiemonster.get = function (cookieName) {
var cstring = cm_readCookie(cookieName);
if (cstring.indexOf('<#&type=ArrayVals>') != -1) {
var carray = cstring.split(',');
for (var i = 0; i < carray.length; i++) {
carray[i] = cm_dirty(carray[i]);
}
if (carray[0] == '<#&type=ArrayVals>') {
carray.splice(0, 1);
}
return carray;
} else {
return cm_dirty(cstring);
}
};
cookiemonster.set = function (cookieName, value, expDays) {
if (value instanceof Array) {
cm_createCookie(cookieName, cm_arrayAsString(value), expDays);
}
else { cm_createCookie(cookieName, cm_clean(value), expDays); }
};
cookiemonster.eraseCookie = function (name) {
cm_createCookie(name, "", -1);
};
function cm_replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
};
function cm_clean(ret) {
ret = cm_replaceAll(ret.toString(), ',', '&#44');
ret = cm_replaceAll(ret.toString(), ';', '&#59');
return ret;
};
function cm_dirty(ret) {
ret = cm_replaceAll(ret, '&#44', ',');
ret = cm_replaceAll(ret, '&#59', ';');
return ret;
};
function cm_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 cm_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;
};
function cm_arrayAsString(array) {
var ret = "<#&type=ArrayVals>"; //escapes, tells that string is array
for (var i = 0; i < array.length; i++) {
ret = ret + "," + cm_clean(array[i]);
}
return ret;
};

Create array in cookie using jQUery?
var list = new cookieList("test"); $(img).one('click', function(i){ while($('.selected').length < 3) {
$(this).parent()
.addClass("selected")
.append(setup.config.overlay);
//$.cookie(setup.config.COOKIE_NAME, d, setup.config.OPTS);
var index = $(this).parent().index();
// suppose this array go into cookies.. but failed
list.add( index );
var count = 'You have selected : <span>' + $('.selected').length + '</span> deals';
if( $('.total').length ){
$('.total').html(count);
}
} });

I agree with other comments - you should not be doing this and you should be using JSON. However, to answer your question you could hack this by storing the array as a comma-delimited string. Lets say you wanted to save a the following Javascript array into a cookie:
var a = ['peter','esther','john'];
You could define a cookie string, then iterate over the array:
// Create a timestamp in the future for the cookie so it is valid
var nowPreserve = new Date();
var oneYear = 365*24*60*60*1000; // one year in milliseconds
var thenPreserve = nowPreserve.getTime() + oneYear;
nowPreserve.setTime(thenPreserve);
var expireTime = nowPreserve.toUTCString();
// Define the cookie id and default string
var cookieId = 'arrayCookie';
var cookieStr = '';
// Loop over the array
for(var i=0;i<a.length;i++) {
cookieStr += a[i]+',';
}
// Remove the last comma from the final string
cookieStr = cookieStr.substr(0,cookieStr.length-1);
// Now add the cookie
document.cookie = cookieId+'='+cookieStr+';expires='+expireTime+';domain='+document.domain;
In this example, you would get the following cookie stored (if your domain is www.example.com):
arrayCookie=peter,ester,john;expires=1365094617464;domain=www.example.com

I've created this easy way to get cookies. It'll give error if execute here, but it's functional
var arrayOfCookies = [];
function parseCookieToArray()
{
var cookies = document.cookie;
var arrayCookies = cookies.split(';');
arrayCookies.map(function(originalValue){
var name = originalValue.split('=')[0];
var value = originalValue.split('=')[1];
arrayOfCookies[name] = value;
});
}
console.log(arrayOfCookies); //in my case get out: [language: 'en_US', country: 'brazil']
parseCookieToArray();
New
My new obj to create get cookies
cookie = {
set: function(name, value) {
document.cookie = name+"="+value;
},
get: function(name) {
cookies = document.cookie;
r = cookies.split(';').reduce(function(acc, item){
let c = item.split('='); //'nome=Marcelo' transform in Array[0] = 'nome', Array[1] = 'Marcelo'
c[0] = c[0].replace(' ', ''); //remove white space from key cookie
acc[c[0]] = c[1]; //acc == accumulator, he accomulates all data, on ends, return to r variable
return acc; //here do not return to r variable, here return to accumulator
},[]);
}
};
cookie.set('nome', 'Marcelo');
cookie.get('nome');

Here's the simplest form of adding a cookie in array format.
function add_to_cookie(variable, value) {
var d = new Date();
d.setTime(d.getTime() + (90 * 24 * 60 * 60 * 1000)); //equivalent to 1 month
var expires = "expires=" + d.toUTCString();
document.cookie = "cookie_name[" + variable + "]" + "=" + value + ";" + expires + ';path=/';
}

For that example you can do it quite easily:
Make Cookies:
///W3Schools Cookie Code:
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";";
}
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 "";
}
///My Own Code:
for(a=0;a<b.length;a++){
setCookie(b[a],b[a],periodoftime);
}
Retrieve Array:
for(a=0;a<b.length;a++){
b[a] = getCookie(b[a])
}
For any array with other value types besides strings:
Make Cookies:
///Replace MyCode above With:
if(typeof b[a] === 'string'){
setCookie(b[a],b[a],periodoftime);
}else{
setCookie(b[a].toString,b[a],periodoftime);
}
Retrieve Array:
for(a=0;a<b.length;a++){
if(typeof b[a] === 'string'){
b[a] = getCookie(b[a])
}else{
b[a] = getCookie(b[a].toString)
}
}
The only flaw is that identical values cannot be retrieved.
No JQuery needed, comma seperation or JSON.

Added remove to cookiemonster
// remove item
cookiemonster.remove('series', 's6', 30); //returns array with values ['s1', 's2', 's3', 's4', 's5', 's7', 's8']
cookiemonster.remove = function (cookieName, item, expDays) {
var cookievalue = cookiemonster.get(cookieName);
//Find the item
for( var i = 0; i < cookievalue.length; i++) {
if ( cookievalue[i] === item) {
cookievalue.splice(i, 1);
}
}
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
};

You can save a lot of data within a single cookie and return it as an array, try this
function setCookie(cookieKey, cookieValue) {
var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)idpurchase\s*\=\s*([^;]*).*$)|^.*$/, "$1")
var idPurchase = cookie.split(",")
idPurchase.push(cookieValue)
document.cookie = cookieKey+"=" + idPurchase
console.log("Id das compras efetuadas :",idPurchase)
$("#purchases_ids option:last").after($('<option onclick="document.getElementById("input_class1").value='+cookieValue+'" value="'+cookieValue+'">'+cookieValue+'</option>'))
}
checkCookie()
function checkCookie() {
var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)idpurchase\s*\=\s*([^;]*).*$)|^.*$/, "$1")
var idPurchase = cookie.split(",")
console.log("Id das compras efetuadas :",idPurchase)
for (i = 1; i < idPurchase.length; i++) {
$("#purchases_ids option:last").after($('<option value="'+idPurchase[i]+'">'+idPurchase[i]+'</option>'))
}
purchases_ids.addEventListener("change",changeSpeed)
}
in this project that I created I store values ​​in arrays, codePen is not allowing the storage of cookies, but in the example below you can get a complete picture, just study the implementation
Github project
Open in Gitpod

Related

how to change url parameter value in browser [duplicate]

I have this URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
what I need is to be able to change the 'rows' url param value to something i specify, lets say 10. And if the 'rows' doesn't exist, I need to add it to the end of the url and add the value i've already specified (10).
I've extended Sujoy's code to make up a function.
/**
* http://stackoverflow.com/a/10997390/11236
*/
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
Function Calls:
var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');
window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));
Updated version that also take care of the anchors on the URL.
function updateURLParameter(url, param, paramVal)
{
var TheAnchor = null;
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL)
{
var tmpAnchor = additionalURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheAnchor)
additionalURL = TheParams;
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++)
{
if(tempArray[i].split('=')[0] != param)
{
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
else
{
var tmpAnchor = baseURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheParams)
baseURL = TheParams;
}
if(TheAnchor)
paramVal += "#" + TheAnchor;
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
I think you want the query plugin.
E.g.:
window.location.search = jQuery.query.set("rows", 10);
This will work regardless of the current state of rows.
Quick little solution in pure js, no plugins needed:
function replaceQueryParam(param, newval, search) {
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : '');
}
Call it like this:
window.location = '/mypage' + replaceQueryParam('rows', 55, window.location.search)
Or, if you want to stay on the same page and replace multiple params:
var str = window.location.search
str = replaceQueryParam('rows', 55, str)
str = replaceQueryParam('cols', 'no', str)
window.location = window.location.pathname + str
edit, thanks Luke: To remove the parameter entirely, pass false or null for the value: replaceQueryParam('rows', false, params). Since 0 is also falsy, specify '0'.
To answer my own question 4 years later, after having learned a lot. Especially that you shouldn't use jQuery for everything. I've created a simple module that can parse/stringify a query string. This makes it easy to modify the query string.
You can use query-string as follows:
// parse the query string into an object
var q = queryString.parse(location.search);
// set the `row` property
q.rows = 10;
// convert the object to a query string
// and overwrite the existing query string
location.search = queryString.stringify(q);
A modern approach to this is to use native standard based URLSearchParams. It's supported by all major browsers, except for IE where they're polyfills available
const paramsString = "site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc"
const searchParams = new URLSearchParams(paramsString);
searchParams.set('rows', 10);
console.log(searchParams.toString()); // return modified string.
Ben Alman has a good jquery querystring/url plugin here that allows you to manipulate the querystring easily.
As requested -
Goto his test page here
In firebug enter the following into the console
jQuery.param.querystring(window.location.href, 'a=3&newValue=100');
It will return you the following amended url string
http://benalman.com/code/test/js-jquery-url-querystring.html?a=3&b=Y&c=Z&newValue=100#n=1&o=2&p=3
Notice the a querystring value for a has changed from X to 3 and it has added the new value.
You can then use the new url string however you wish e.g
using document.location = newUrl or change an anchor link etc
This is the modern way to change URL parameters:
function setGetParam(key,value) {
if (history.pushState) {
var params = new URLSearchParams(window.location.search);
params.set(key, value);
var newUrl = window.location.origin
+ window.location.pathname
+ '?' + params.toString();
window.history.pushState({path:newUrl},'',newUrl);
}
}
you can do it via normal JS also
var url = document.URL
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var aditionalURL = tempArray[1];
var temp = "";
if(aditionalURL)
{
var tempArray = aditionalURL.split("&");
for ( var i in tempArray ){
if(tempArray[i].indexOf("rows") == -1){
newAdditionalURL += temp+tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp+"rows=10";
var finalURL = baseURL+"?"+newAdditionalURL+rows_txt;
Use URLSearchParams to check, get and set the parameters value into URL
Here is the example to get the current URL and set new parameter and update the URL or reload the page as per your needs
var rows = 5; // value that you want to set
var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
url.search = url.searchParams;
url = url.toString();
// if you want to append into URL without reloading the page
history.pushState({}, null, url);
// want to reload the window with a new param
window.location = url;
2020 Solution: sets the variable or removes iti if you pass null or undefined to the value.
var setSearchParam = function(key, value) {
if (!window.history.pushState) {
return;
}
if (!key) {
return;
}
var url = new URL(window.location.href);
var params = new window.URLSearchParams(window.location.search);
if (value === undefined || value === null) {
params.delete(key);
} else {
params.set(key, value);
}
url.search = params;
url = url.toString();
window.history.replaceState({url: url}, null, url);
}
Would a viable alternative to String manipulation be to set up an html form and just modify the value of the rows element?
So, with html that is something like
<form id='myForm' target='site.fwx'>
<input type='hidden' name='position' value='1'/>
<input type='hidden' name='archiveid' value='5000'/>
<input type='hidden' name='columns' value='5'/>
<input type='hidden' name='rows' value='20'/>
<input type='hidden' name='sorting' value='ModifiedTimeAsc'/>
</form>
With the following JavaScript to submit the form
var myForm = document.getElementById('myForm');
myForm.rows.value = yourNewValue;
myForm.submit();
Probably not suitable for all situations, but might be nicer than parsing the URL string.
URL query parameters can be easily modified using URLSearchParams and History interfaces:
// Construct URLSearchParams object instance from current URL querystring.
var queryParams = new URLSearchParams(window.location.search);
// Set new or modify existing parameter value.
//queryParams.set("myParam", "myValue");
queryParams.set("rows", "10");
// Replace current querystring with the new one.
history.replaceState(null, null, "?"+queryParams.toString());
Alternatively instead of modifying current history entry using replaceState() we can use pushState() method to create a new one:
history.pushState(null, null, "?"+queryParams.toString());
https://zgadzaj.com/development/javascript/how-to-change-url-query-parameter-with-javascript-only
You can use this my library to do the job: https://github.com/Mikhus/jsurl
var url = new Url('site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc');
url.query.rows = 10;
alert( url);
Consider this one:
const myUrl = new URL("http://www.example.com?columns=5&rows=20");
myUrl.searchParams.set('rows', 10);
console.log(myUrl.href); // http://www.example.com?columns=5&rows=10
myUrl.searchParams.set('foo', 'bar'); // add new param
console.log(myUrl.href); // http://www.example.com?columns=5&rows=10&foo=bar
It will do exactly the same thing you required. Please note URL must have correct format. In your example you have to specify protocol (either http or https)
I wrote a little helper function that works with any select. All you need to do is add the class "redirectOnChange" to any select element, and this will cause the page to reload with a new/changed querystring parameter, equal to the id and value of the select, e.g:
<select id="myValue" class="redirectOnChange">
<option value="222">test222</option>
<option value="333">test333</option>
</select>
The above example would add "?myValue=222" or "?myValue=333" (or using "&" if other params exist), and reload the page.
jQuery:
$(document).ready(function () {
//Redirect on Change
$(".redirectOnChange").change(function () {
var href = window.location.href.substring(0, window.location.href.indexOf('?'));
var qs = window.location.href.substring(window.location.href.indexOf('?') + 1, window.location.href.length);
var newParam = $(this).attr("id") + '=' + $(this).val();
if (qs.indexOf($(this).attr("id") + '=') == -1) {
if (qs == '') {
qs = '?'
}
else {
qs = qs + '&'
}
qs = qs + newParam;
}
else {
var start = qs.indexOf($(this).attr("id") + "=");
var end = qs.indexOf("&", start);
if (end == -1) {
end = qs.length;
}
var curParam = qs.substring(start, end);
qs = qs.replace(curParam, newParam);
}
window.location.replace(href + '?' + qs);
});
});
Using javascript URL:
var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
window.location = url;
var url = new URL(window.location.href);
var search_params = url.searchParams;
search_params.set("param", value);
url.search = search_params.toString();
var new_url = url.pathname + url.search;
window.history.replaceState({}, '', new_url);
Here I have taken Adil Malik's answer and fixed the 3 issues I identified with it.
/**
* Adds or updates a URL parameter.
*
* #param {string} url the URL to modify
* #param {string} param the name of the parameter
* #param {string} paramVal the new value for the parameter
* #return {string} the updated URL
*/
self.setParameter = function (url, param, paramVal){
// http://stackoverflow.com/a/10997390/2391566
var parts = url.split('?');
var baseUrl = parts[0];
var oldQueryString = parts[1];
var newParameters = [];
if (oldQueryString) {
var oldParameters = oldQueryString.split('&');
for (var i = 0; i < oldParameters.length; i++) {
if(oldParameters[i].split('=')[0] != param) {
newParameters.push(oldParameters[i]);
}
}
}
if (paramVal !== '' && paramVal !== null && typeof paramVal !== 'undefined') {
newParameters.push(param + '=' + encodeURI(paramVal));
}
if (newParameters.length > 0) {
return baseUrl + '?' + newParameters.join('&');
} else {
return baseUrl;
}
}
In the URLSearchParams documentation, there's a very clean way of doing this, without affecting the history stack.
// URL: https://example.com?version=1.0
const params = new URLSearchParams(location.search);
params.set('version', 2.0);
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?version=2.0
Similarily, to remove a parameter
params.delete('version')
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?
let url= new URL("https://example.com/site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc")
url.searchParams.set('rows', 10)
console.log(url.toString())
Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the URL:
window.history.replaceState('object or string', 'Title', 'page.html' + editParams('sorting', ModifiedTimeAsc));
// background functions below:
// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
key = encodeURI(key);
var params = getSearchParameters();
if (Object.keys(params).length === 0) {
if (value !== false)
return '?' + key + '=' + encodeURI(value);
else
return '';
}
if (value !== false)
params[key] = encodeURI(value);
else
delete params[key];
if (Object.keys(params).length === 0)
return '';
return '?' + $.map(params, function (value, key) {
return key + '=' + value;
}).join('&');
}
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
My solution:
const setParams = (data) => {
if (typeof data !== 'undefined' && typeof data !== 'object') {
return
}
let url = new URL(window.location.href)
const params = new URLSearchParams(url.search)
for (const key of Object.keys(data)) {
if (data[key] == 0) {
params.delete(key)
} else {
params.set(key, data[key])
}
}
url.search = params
url = url.toString()
window.history.replaceState({ url: url }, null, url)
}
Then just call "setParams" and pass an object with data you want to set.
Example:
$('select').on('change', e => {
const $this = $(e.currentTarget)
setParams({ $this.attr('name'): $this.val() })
})
In my case I had to update a html select input when it changes and if the value is "0", remove the parameter. You can edit the function and remove the parameter from the url if the object key is "null" as well.
Hope this helps yall
If you want to change the url in address bar:
const search = new URLSearchParams(location.search);
search.set('rows', 10);
location.search = search.toString();
Note, changing location.search reloads the page.
Here is a simple solution using the query-string library.
const qs = require('query-string')
function addQuery(key, value) {
const q = qs.parse(location.search)
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
// if you are using Turbolinks
// add this: Turbolinks.visit(url)
}
// Usage
addQuery('page', 2)
If you are using react without react-router
export function useAddQuery() {
const location = window.location;
const addQuery = useCallback(
(key, value) => {
const q = qs.parse(location.search);
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
},
[location]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
If you are using react with react-router
export function useAddQuery() {
const location = useLocation();
const history = useHistory();
const addQuery = useCallback(
(key, value) => {
let pathname = location.pathname;
let searchParams = new URLSearchParams(location.search);
searchParams.set(key, value);
history.push({
pathname: pathname,
search: searchParams.toString()
});
},
[location, history]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
PS: qs is the import from query-string module.
Another variation on Sujoy's answer. Just changed the variable names & added a namespace wrapper:
window.MyNamespace = window.MyNamespace || {};
window.MyNamespace.Uri = window.MyNamespace.Uri || {};
(function (ns) {
ns.SetQueryStringParameter = function(url, parameterName, parameterValue) {
var otherQueryStringParameters = "";
var urlParts = url.split("?");
var baseUrl = urlParts[0];
var queryString = urlParts[1];
var itemSeparator = "";
if (queryString) {
var queryStringParts = queryString.split("&");
for (var i = 0; i < queryStringParts.length; i++){
if(queryStringParts[i].split('=')[0] != parameterName){
otherQueryStringParameters += itemSeparator + queryStringParts[i];
itemSeparator = "&";
}
}
}
var newQueryStringParameter = itemSeparator + parameterName + "=" + parameterValue;
return baseUrl + "?" + otherQueryStringParameters + newQueryStringParameter;
};
})(window.MyNamespace.Uri);
Useage is now:
var changedUrl = MyNamespace.Uri.SetQueryStringParameter(originalUrl, "CarType", "Ford");
I too have written a library for getting and setting URL query parameters in JavaScript.
Here is an example of its usage.
var url = Qurl.create()
, query
, foo
;
Get query params as an object, by key, or add/change/remove.
// returns { foo: 'bar', baz: 'qux' } for ?foo=bar&baz=qux
query = url.query();
// get the current value of foo
foo = url.query('foo');
// set ?foo=bar&baz=qux
url.query('foo', 'bar');
url.query('baz', 'qux');
// unset foo, leaving ?baz=qux
url.query('foo', false); // unsets foo
I was looking for the same thing and found: https://github.com/medialize/URI.js which is quite nice :)
-- Update
I found a better package: https://www.npmjs.org/package/qs it also deals with arrays in get params.
No library, using URL() WebAPI (https://developer.mozilla.org/en-US/docs/Web/API/URL)
function setURLParameter(url, parameter, value) {
let url = new URL(url);
if (url.searchParams.get(parameter) === value) {
return url;
}
url.searchParams.set(parameter, value);
return url.href;
}
This doesn't work on IE: https://developer.mozilla.org/en-US/docs/Web/API/URL#Browser_compatibility
I know this is an old question. I have enhanced the function above to add or update query params. Still a pure JS solution only.
function addOrUpdateQueryParam(param, newval, search) {
var questionIndex = search.indexOf('?');
if (questionIndex < 0) {
search = search + '?';
search = search + param + '=' + newval;
return search;
}
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
var indexOfEquals = query.indexOf('=');
return (indexOfEquals >= 0 ? query + '&' : query + '') + (newval ? param + '=' + newval : '');
}
my function support removing param
function updateURLParameter(url, param, paramVal, remove = false) {
var newAdditionalURL = '';
var tempArray = url.split('?');
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var rows_txt = '';
if (additionalURL)
newAdditionalURL = decodeURI(additionalURL) + '&';
if (remove)
newAdditionalURL = newAdditionalURL.replace(param + '=' + paramVal, '');
else
rows_txt = param + '=' + paramVal;
window.history.replaceState('', '', (baseURL + "?" + newAdditionalURL + rows_txt).replace('?&', '?').replace('&&', '&').replace(/\&$/, ''));
}

Sharing Cookie among browser tabs without refreshing tab in javascript

hi i am designing a real estate website and i have many ads in it i add an option to every of my ads and if user click on "add to favorites" that ad's id and url saves in a cookie and retrieve in "favorite page" thus user can review that certain ad every time he or she wants. each of my ads have a address like this localhost/viewmore.php?ID=a number
totally saving process in cookie works fine but recently i realized something. consider i visit one of my ads with this address localhost/viewmore.php?ID=10 and click on "add to favorite" then if i open another page with this address localhost/viewmore.php?ID=8 and then i read my cookie in "favorite page" i will see this result
[{"favoriteid":"10","url":"http://localhost/viewcookie.php?ID=10"},{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8"}]
which is perfectly true and it is what i expect.
the problem
now consider unlike the previous case i open both of ads and then click on "add to favorite" on first ad and then go to second ad (without any refreshing) and click on "add to favorite" on second ad this time if i read my cookie in "favorite page" i will see this result
[{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8"}]
which is not true i want two see both of ad's id and url in my cookie not just last one.
ps: i use push() method to add new object to cookie array i think i have to update it every time after click? any idea thanks
/*
* 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 isAlready(){
var is = false;
$.each(faves,function(index,value){
if(this.url == window.location.href){
console.log(index);
faves.splice(index,1);
is = true;
}
});
return is;
}
$(function(){
var url = window.location.href; // current page url
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);
}
// this is the part i think i have to update every time without refreshing*******************************
$(document.body).on('click','#addTofav',function(e){
e.preventDefault();
if(isAlready()){
} else {
var fav = {'favoriteid':favID,'url':url};
faves.push(fav);
}
//*******************************************************************************************************
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
});
var myfaves = JSON.parse(readCookie('favespages'));
if(myfaves){
faves = myfaves;
} else {
faves = new Array();
}
});
Your problem is that you are looking at variable faves, which is initialized at document load, but it isn't being updated as cookie changes.
The second page looks at the variable, sees no favorites from first page, because it doesn't actually look at cookie.
Then, it just resets the cookie with it's values.
Here is the full code, with added functionality from chat:
/*
* 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;
}
/*
* Erase cookie with name.
* You can also erase/delete the cookie with name.
*/
function eraseCookie(name) {
createCookie(name, '', -1);
}
var faves = {
add: function (new_obj) {
var old_array = faves.get();
old_array.push(new_obj);
faves.create(old_array);
},
remove_index: function (index) {
var old_array = faves.get();
old_array.splice(index, 1);
faves.create(old_array);
},
remove_id: function (id) {
var old_array = faves.get();
var id_index = faves.get_id_index(id);
faves.remove_index(id_index);
},
create: function (arr) {
var stringified = JSON.stringify(arr);
createCookie('favespages', stringified);
},
get: function () {
return JSON.parse(readCookie('favespages')) || [];
},
get_id_index: function (id) {
var old_array = faves.get();
var id_index = -1;
$.each(old_array, function (index, val) {
if (val.id == id) {
id_index = index;
}
});
return id_index;
},
update_list: function () {
$("#appendfavs").empty();
$.each(faves.get(), function (index, value) {
var element = '<li class="' + index + '"><h4>' + value.id + '</h4> Open page ' +
'Remove me';
$('#appendfavs').append(element);
});
}
}
$(function () {
var url = window.location.href;
$(document.body).on('click', '#addTofav', function (e) {
var pageId = window.location.search.match(/ID=(\d+)/)[1];
if (faves.get_id_index(pageId) !== -1) {
faves.remove_id(pageId);
}
else {
faves.add({
id: pageId,
url: url
});
}
faves.update_list();
});
$(document.body).on('click', '.remove', function () {
var url = $(this).data('id');
faves.remove_id(url);
faves.update_list();
});
$(window).on('focus', function () {
faves.update_list();
});
faves.update_list();
});

how to pass variable to next page with cookies

I am designing a real estate website. I have many ads in my website and thanks to my friend Arsh Singh I create a 'favorite' or 'save' button on each of the posts that will save the selected page title in a certain page based on cookies for user to review the post when ever he or she wants.
Now i want to send ad's id to the favorite page when user click on "add to favorites" thus based on id i can fetch that certain ad data from database .
can i do this? how? this is my current code and it can only send page title to the favorite page. any idea?
<!DOCTYPE html>
<html>
<head>
<title>New page name</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src=favoritecookie.js></script>
</head>
<body>
Add me to fav
<ul id="appendfavs">
</ul>
<?php
error_reporting(0);
include("config.php");
(is_numeric($_GET['ID'])) ? $ID = $_GET['ID'] : $ID = 1;
$result = mysqli_query($connect,"SELECT*FROM ".$db_table." WHERE idhome = $ID");
?>
<?php while($row = mysqli_fetch_array($result)):
$price=$row['price'];
$rent=$row['rent'];
$room=$row['room'];
$date=$row['date'];
?>
<?php
echo"price";
echo"room";
echo"date";
?>
<?php endwhile;?>
</body>
</html>
//favoritecookie.js
/*
* 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;
}
/*
* Erase cookie with name.
* You can also erase/delete the cookie with name.
*/
function eraseCookie(name) {
createCookie(name, '', -1);
}
var faves = new Array();
function isAlready(){
var is = false;
$.each(faves,function(index,value){
if(this.url == window.location.href){
console.log(index);
faves.splice(index,1);
is = true;
}
});
return is;
}
$(function(){
var url = window.location.href; // current page url
$(document.body).on('click','#addTofav',function(e){
e.preventDefault();
var pageTitle = $(document).find("title").text();
if(isAlready()){
} else {
var fav = {'title':pageTitle,'url':url};
faves.push(fav);
}
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
$(document.body).on('click','.remove',function(){
var id = $(this).data('id');
faves.splice(id,1);
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.title+'</h4> Open page '+
'Remove me';
$('#appendfavs').append(element);
});
});
JSON in Cookie
You can use JSON to store the details (id, post name, etc) into a cookie by serialising the JSON:
jquery save json data object in cookie
However you should not store database table names in cookies for security's sake.
PHP cookies access
https://davidwalsh.name/php-cookies
I would use pure PHP... setcookie() to place a cookie, and read it back when needed using PHP $_COOKIE. Since there would be a need to store a lot of data, structured, related or not, I would then create an associative array, fill it accordingly and then use PHP serialize() it before save it in a cookie; unserialize() when reading:
Saving:
a) $data = array("ID"=>value, "otherdata"=>value...etc);
b) $dataPacked = serialize($data);
c) setcookie("cookieName", $dataPacked);
Reading:
a) $dataPacked = $_COOKIE["cookieName"];
b) $data = unserialize($dataPacked);
Then use $data array as needed. If I would need some Javascript with that data I would simply do:
<script>
var jsVar = "<?php echo $data['key'];?>";
Or go fancier with loops to write more vars from $data, etc.
Here is refactored code that works better (from SO answer):
/*
* 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;
}
/*
* Erase cookie with name.
* You can also erase/delete the cookie with name.
*/
function eraseCookie(name) {
createCookie(name, '', -1);
}
var faves = {
add: function (new_obj) {
var old_array = faves.get();
old_array.push(new_obj);
faves.create(old_array);
},
remove_index: function (index) {
var old_array = faves.get();
old_array.splice(index, 1);
faves.create(old_array);
},
remove_id: function (id) {
var old_array = faves.get();
var id_index = faves.get_id_index(id);
faves.remove_index(id_index);
},
create: function (arr) {
var stringified = JSON.stringify(arr);
createCookie('favespages', stringified);
},
get: function () {
return JSON.parse(readCookie('favespages')) || [];
},
get_id_index: function (id) {
var old_array = faves.get();
var id_index = -1;
$.each(old_array, function (index, val) {
if (val.id == id) {
id_index = index;
}
});
return id_index;
},
update_list: function () {
$("#appendfavs").empty();
$.each(faves.get(), function (index, value) {
var element = '<li class="' + index + '"><h4>' + value.id + '</h4> Open page ' +
'Remove me';
$('#appendfavs').append(element);
});
}
}
$(function () {
var url = window.location.href;
$(document.body).on('click', '#addTofav', function (e) {
var pageId = window.location.search.match(/ID=(\d+)/)[1];
if (faves.get_id_index(pageId) !== -1) {
faves.remove_id(pageId);
}
else {
faves.add({
id: pageId,
url: url
});
}
faves.update_list();
});
$(document.body).on('click', '.remove', function () {
var url = $(this).data('id');
faves.remove_id(url);
faves.update_list();
});
$(window).on('focus', function () {
faves.update_list();
});
faves.update_list();
});
finally i got the answer. replace this javascript code instead of question javascript (favoritecookie.js) and you will see that it works like a charm.with this u code can save id in cookie and then retrieve it where ever u want
<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 isAlready(){
var is = false;
$.each(faves,function(index,value){
if(this.url == window.location.href){
console.log(index);
faves.splice(index,1);
is = true;
}
});
return is;
}
$(function(){
var url = window.location.href; // current page url
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(){
if(isAlready()){
} else {
var fav = {'favoriteid':favID,'url':url};
faves.push(fav);//The push() method adds new items (fav) to the end of an array (faves), and returns the new length.
}
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
$(document.body).on('click','.remove',function(){
var id = $(this).data('id');
faves.splice(id,1);
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> '+
'Remove me';
$('#appendfavs').append(element);
});
});
</script>

Firebase Failed to Increment Counter

I have two firebase scripts; one of them is working fine but other not. I don't have any idea what is going on. Those two scripts are based on same logic. Only difference is that counter 2 data is always incremented irrespective of website home page or post page while counter 1 data is incremented only it is post page (i.e. pathname!='/'). Fortunately counter 1 is working fine but counter 2 not. I don't have any idea what i'm doing wrong..
Please help me to get rid of this bug. Any kind of help would be appreciated.
$(function(){
var parentDataRef = 'https://blablabla.firebaseio.com/';
//counter 1
var postRef = new Firebase(parentDataRef+'one');
getFirebaseData(postRef,'post',function(pData){
alert(pData);
});
//counter 2
var blogRef = new Firebase(parentDataRef+'two');
getFirebaseData(blogRef,'blog',function(bData){
alert(bData);
});
});
//get Firebase data
function getFirebaseData(r,bp,back){ //Reference, Blog or Post, Return data
var doctitle = document.title;
r.once('value', function(e) {
var data=e.val();
if (data==null){data=1;}
else if (getCookie(doctitle)!='yes'){
if (bp=='post' && window.location.pathname!='/') {data++;}
else if (bp=='blog') {data++;}
}
r.set(data);
back(data);
setCookie(doctitle,'yes',7);
});
}
//set Cookie Data
function setCookie(cname,cvalue,exdays){
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = 'expires=' + d.toGMTString();
document.cookie = cname+'='+cvalue+'; '+expires+'; path=/';
}
//get Cookie Data
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 '';
}
Can I suggest to use transactions your counters ?
var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
return (current_value || 0) + 1;
});

Javascript - Using cookies to store an integer

I am trying to use a cookie to store a single integer, so when the user refreshes the page I am able to retrieve the previous number they were on (in an attempt to stop doubles of a video appearing).
What would the minimum requirements be to accomplish this?
var randomNumber = Math.floor((Math.random()*10)+1);
document.cookie=(randomNumber);
Setting a cookie:
document.cookie = 'mycookie=' + randomNumber + ";max-age=" + (300) + ";";
Reading a cookie:
var cookie = document.cookie;
alert(decodeURIComponent(cookie));
The cookie contains some other random stuff like push=1 as well as mycookie. Should I be setting the cookie to null before I add the randomNumber?
As far as getting the value of mycookie would I just assign the cookie to a string and parse mycookie from it?
Tamil's comment is solid. Use these quirksmode functions if you ever wish to surpass minimal cookie usage:
cookie_create = function (name,value,days) {
var expires, date;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
expires = date = null;
};
cookie_read = function (name) {
var nameEQ = name + "=",
ca = document.cookie.split(';'),
len = ca.length,
i, c;
for(i = 0; i < len; ++i) {
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);
}
nameEQ = name = ca = i = c = len = null;
return null;
};
cookie_erase = function (name){
cookie_create(name,"",-1);
name = null;
};
You could use document.cookie to read/write cookies in javascript:
document.cookie = 'mycookie=' + randomNumber + '; path=/';
And if you wanted the cookie to be persistent even after the user closing his browser you could specify an expires date.

Categories

Resources