How to save jQuery object in a cookie?

jquery save json data object in cookie

  • How do I save JSON data in a cookie? My JSON data looks like this $("#ArticlesHolder").data('15', {name:'testname', nr:'4',price:'400'}); $("#ArticlesHolder").data('25', {name:'name2', nr:'1', price:'100'}); $("#ArticlesHolder").data('37', {name:'name3', nr:'14', price:'60'}); And I whant to do something like var dataStore = $.cookie("basket-data", $("#ArticlesHolder").data()); and to retrive the data i want to load it into "$("#ArticlesHolder")" like $.each($.cookie("basket-data"), function(i,e){ $("#ArticlesHolder").data(i, e); }); does anyone know if im on the right trac or should this be done in some other way? Simply put, how do i put and pull json data from a cookie?

  • Answer:

    You can seriaize the data as JSON, like this: $.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data())); Then to get it from the cookie: $("#ArticlesHolder").data(JSON.parse($.cookie("basket-data"))); This relies on https://developer.mozilla.org/en/json#Using_native_JSON to serialize/deserialize your data object, for older browsers (IE<8) include http://www.json.org/js.html to get the JSON functionality.

Marthin at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

use JSON.stringify(userData) to coverty json to string. var dataStore = $.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data())); and for getting back form cookie use JSON.parse() var data=JSON.parse($.cookie("basket-data"))

WebDev

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.