Reputation: 132
first of all i know that there are many questions similar to mine. Of course i have read them all, but i couldn't find the solution or understand how to solve my problem. here is the main problem: i have an associative array in java script which i want to serialize it and save it in a cookie, then i want to read this cookie with php by using unserialize method. so i can't find a proper way to serialize the associative array.
there is javascript
function renewCookie(){
var myArray = {radius: radius, type:type, date:price, name:company}
serializeValue = JSON.stringify(myArray);/* i used this serialize function that i found on web http://phpjs.org/functions/serialize/ but it didn't work.*/
createCookie('parameters',serializeValue ,999);
}
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=/";
}
there is php
<?php
if (isset($_COOKIE["parameters"])){
$UserParam = json_decode($_COOKIE["parameters"]);/*I unserialize the cookie because i suppose that it is serialized*/
echo"<script>function readCookie(){ getLocationFunction(".$UserParam["radius"].",\"".$UserParam["type"]."\",\"".$UserParam["date"]."\",\"".$UserParam["name"]."\")}</script>";
}
else{setcookie("parameters","$defaultParam",time()+3600);}
?>
dose someone know how to read the cookie created by javascript with php? I also explain that i have an associative array because i want to have both multyvalue cookie and the name of the keys. pleas for helping me provide some code. if you want more explanation pleas ask. Thank you in advance!!
update: the code above it works fine with your suggestions, but it works only on firefox and chrome, not in opera, safari and explorer. dose anybody see what i am doing wrong??
Upvotes: 1
Views: 4199
Reputation: 71384
Just use JSON serialization.
in javascript:
serializeValue = JSON.stringify(myArray);
in PHP
$UserParam = json_decode($_COOKIE["parameters"]);
Note that $UserParam
would be on object in this case. If you want to force an associative array use:
$UserParam = json_decode($_COOKIE["parameters"], true);
Upvotes: 3