Javascript JSON.stringify() not working



OK I have spend alot of time trying to figure this out. I am reading a cookie in PHP and and storing it inside an XML file. The cookie is of type array of objects. I then want to set the cookie stored in the xml file with java script. You might ask why I am doing this, I am storing some user information inside the xml file, and i want to set the cookie when the user logs back in.


I am having trouble setting the cookie with Javascript. The JSON.stringify() doesnt seem to be working here. When I do document.cookie in the browser console the cookie is of type object.


Here is my PHP code:



if(isset($_GET['save'])){
$books = $_COOKIE['myBooks'];
$username = $_SESSION['user'];
$users = simplexml_load_file("users.xml");

$user = $users->addChild('user');
$user->addChild('username', $username);
$user->addChild('books', $books);

$users->saveXML("users.xml");
}


This all seems to be working fine. Here is my javascript:



function getPapers(){
delete Array.prototype.toJSON;

loadXML("users.xml", function(xml){

$(xml).find("user").each(function(){
var books = $(this).find("books");
books = decodeURIComponent(books);
books = JSON.stringify(books); //Not working
alert(typeof(books)); //returns object
document.cookie = "myBooks=" + books;
})
});

}


This is the content of books: "[{"bookName":"The Whale","bookCode":"THW12","copies":"1"}]"


Am i doing something wrong? I need the cookie to be stored as a JSON string.


No comments:

Post a Comment