Answer the question
In order to leave comments, you need to log in
How to return PHP array from JSON in cookies created by jQuery Cookie plugin?
Hello, I am writing an online store, without CMS, such a task arose. There is WISHLIST, which I decided to store in cookies, which, in my opinion, is convenient and does not require user registration and storage of the wishlist in the database. On the product cards themselves there are buttons that add the product to the Wishlist - I implemented this with the JQuery Cookie plugin, the wishitems cookie is set on the first visit and contains an empty array - the code is as follows
// это при первом входе создается кука с пустым массивом
if ($.cookie('wishitems') == null) {
var start = [];
$.cookie("wishitems", JSON.stringify(start));
}
// Сама функция с комментариями
function wishlist_add() {
var wishitems = $.parseJSON($.cookie("wishitems")); // Кука превращается из JSON -> array
var current_id = $('#kuka').val(); // Для примера берется ID из инпута пока
var alredy_added = $.inArray(current_id, wishitems); // Проверяется нет ли уже такого ID в массиве
if (alredy_added === -1) {
wishitems.push(current_id); // Если нету то добавляется в массив
$.cookie("wishitems", JSON.stringify(wishitems)); // Превращается в JSON и переписывает куку
}
}
// Пробы
print_r($_COOKIE['wishitems']); // просто проверяю что выводит - вывод такой ["\"11\",\"12\"] что уже что то не то
$abc = ($_COOKIE['wishitems']); // пробую как есть
$result = json_encode($abc, true); // но JSON в массив PHP не энкодится
$abc = stripcslashes($_COOKIE['wishitems']); // пробую убрать слеши результат ["11","12"]
$result = json_encode($abc, true); // но JSON в массив PHP не энкодится
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question