M
M
malayamarisha2020-03-18 07:54:47
AJAX
malayamarisha, 2020-03-18 07:54:47

How to record product ID in cookies?

The functionality of adding goods to favorites has been implemented.
For authorized users, the functionality works correctly, but for an unauthorized user, the product ID is not transmitted.
Example:
1) go to the product
2) click on "Add to favorites"
3) the ID of this product should be recorded in cookies
4) on the page for displaying favorite products, the product ID should be substituted in the filter

1) The product has a "button" for adding a product to favorites (\bitrix\templates\internet-shop\components\bitrix\catalog.element\.default\template.php)

<div class="put_off favorites old">
                                                <a class="favor" onclick="addFavorite" id="<?= $arResult['ID'] ?>"
                                                   data-item="<?= $arResult['ID'] ?>">Отложить</a>
                                            </div>

2) when you click on the button, the background of the button changes, as well as the product ID is sent to the handler (bitrix\templates\internet-shop\components\bitrix\catalog.element\.default\script.js)
function addFavorite(id, action)
{
    var param = 'id='+id+"&action="+action;
    $.ajax({
        url:     '/bitrix/templates/internet-shop/ajax/favorites.php', // URL отправки запроса
        type:     "GET",
        dataType: "html",
        data: param,
        headers: {
            'Cookie': document.cookie
        },
        success: function(response) { // Если Данные отправлены успешно
            //var result = $.parseJSON(response);
            var resultResponse = $.parseJSON(response);
            //if(result == 1)
            if(action == 'add')
            { // Если всё чётко, то выполняем действия, которые показывают, что данные отправлены :)
                $('.favor[data-item="'+id+'"]').addClass('active');
                $('.favorites').addClass('active');
                $('.favor').text('Отложено');
                var wishCount = parseInt($('#want .wishCount').html()) + 1;
                $('#want .wishCount').html(wishCount); // Визуально меняем количество у иконки
                if (wishCount > 0)
                {
                    $('.wishCount').addClass('active');
                }
                console.log(action);
            }
            //if(result == 2)
            if(action == 'delete')
            {
                $('.favor[data-item="'+id+'"]').removeClass('active');
                $('.favorites').removeClass('active');
                $('.favor').text('Отложить');
                var wishCount = parseInt($('#want .wishCount').html()) - 1;
                $('#want .wishCount').html(wishCount); // Визуально меняем количество у иконки
            }
            if (wishCount == '0')
            {
                $('.wishCount').removeClass('active');
            }
        },
        error: function(jqXHR, textStatus, errorThrown){ // Если ошибка, то выкладываем печаль в консоль
            console.log('Error: '+ errorThrown);
        }
    });
}

3) The handler sends this ID to the page /bitrix/templates/internet-shop/ajax/favorites.php
Here the authorization is checked.
if ($_GET['id'])
{
    if (!$USER->IsAuthorized()) // Для неавторизованного
    {
       $arElements = $APPLICATION->get_cookie('favorites');

        if (!in_array($_GET['id'], $arElements))
        {
            $arElements[] = $_GET['id'];
            $result = 1; // Датчик. Добавляем
        }
        else
        {
            $key = array_search($_GET['id'], $arElements); // Находим элемент, который нужно удалить из избранного
            unset($arElements[$key]);
            $result = 2; // Датчик. Удаляем
        }
        $APPLICATION->set_cookie("favorites", serialize($arElements));
    }
    else
    { // Для авторизованного
        $idUser = $USER->GetID();
        $rsUser = CUser::GetByID($idUser);
        $arUser = $rsUser->Fetch();
        $arElements = $arUser['UF_FAVORITES'];  // Достаём избранное пользователя
        if (!in_array($_GET['id'], $arElements)) // Если еще нету этой позиции в избранном
        {
            $arElements[] = $_GET['id'];
            $result = 1;
        } else
        {
            $key = array_search($_GET['id'], $arElements); // Находим элемент, который нужно удалить из избранного
            unset($arElements[$key]);
            $result = 2;
        }
        $USER->Update($idUser, Array("UF_FAVORITES" => $arElements)); // Добавляем элемент в избранное
    }
}
/* Избранное */
echo json_encode($result);
die(); ?>

And depending on the authorization, the product ID is processed.
4) Further, the product ID is available on the page with the list of products, which is filtered by the product ID.
At the moment, only an authorized user works.

For an unauthorized user, the product ID is not stored in cookies.

Tell me, please, what am I doing wrong? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
smilingcheater, 2020-03-18
@malayamarisha

Are you sure you are getting the value from the cookie correctly?
I see that you are serializing the data on save $APPLICATION->set_cookie("favorites", serialize($arElements));
But when you get it back you don't deserialize $arElements = $APPLICATION->get_cookie('favorites'); and for some reason you hope that an array will be returned to you

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question