Reputation: 315
hi 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 java 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
ps: 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 u see i want to save id in cookies by click wich is not acceiable 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();
}
});
Upvotes: 0
Views: 6310
Reputation: 315
thanks to all of my friends ( RIYAJ KHAN and Anubhav)finally i got the answer. replace this javascript code instead of question javascript 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> '+
'<a href="javascript:void(0);" class="remove" data-id="'+index+'">Remove me</a>';
$('#appendfavs').append(element);
});
});
</script>
Upvotes: 0
Reputation: 15292
After looking your requirement,
You should move this
$ID = $_GET['ID'] : $ID = 1;
on Javascript side.As you say,you want better clean code.Don't messup JS and PHP in single file.It's bad one
You should use javascript to access the parameter passed from URL.
var query = window.location.search.substring(1);
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
var ID = (pair[0]=='ID' ? pair[1] :1)
}
Then ID is easily available to your JS.
YOUR JS :
$(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();
});
EDIT :
You can use localStorage. on current page
`localStorage.getItem('ID',10)`
On other page where you want to access it.
localStorage.getItem('ID');
Upvotes: 1
Reputation: 7208
The problem is your javascript, which I assume is in a different file, is not aware of PHP. You can do the following to define the $ID
in the javascript variable
<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;
?>
<!-- This part is what you want -->
<script>
var favID = <?php $ID ?>; // this gets the variable from PHP and saves it in the javascript variable.
document.cookie = 'my_id='+favID+'; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/' // save it to a cookie
</script>
<!-- till here -->
</body>
</html>
Now on some other page here is how you can get the cookie value:
var nameEQ = "my_id=";
var ca = document.cookie.split(';');
var retrieved_id = null
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) retrieved_id = c.substring(nameEQ.length,c.length);
}
console.log(retrieved_id) // here you will find your ID
Now I haven't tested this. Theoretically it should work though.
Upvotes: 1