I have a PHP code and I get id from another page in it I want to save this variable (id) in cookies with JavaScript. I am new in JavaScript but after a lot of search finally I could wrote some codes. this is my current code please take a look at this I think the problem is how I define
var favID = $ID; in my JavaScript code please help me thanks
p.s.: please do not suggest saving cookie with pure PHP because I did it and it works fine but I want to do some fancier stuff with it for example as you see I want to save id in cookies by click which is not accessible with PHP
<html>
<body>
<a id="addTofav">Add me to fav</a>
<?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");
while($row = mysqli_fetch_array($result)):
$price=$row['price'];
$rent=$row['rent'];
$room=$row['room'];
$date=$row['date'];
echo"price";
echo"room";
echo"date";
endwhile;
?>
</body>
</html>
/*
* 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);
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
var favID = (pair[0]=='ID' ? pair[1] :1)
}
$(document.body).on('click','#addTofav',function(){
var fav = {'$ID':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();
}
});
localStorage?