I
I
Ivan K2021-03-11 11:34:24
PHP
Ivan K, 2021-03-11 11:34:24

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 и переписывает куку
    }
}

Further, already on the WISHLIST page, PHP comes into play, there I need to get an array of IDs for the cycle of displaying the goods directly.
// Пробы
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 не энкодится


Yesterday I killed three hours but did not achieve a solution. How to return PHP array from JSON in cookies generated by jQuery Cookie?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NedoKoder, 2021-03-11
@ikonkov

json_decode yuzay, there is an error

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question