A
A
Alexander2021-09-07 17:47:02
1C-Bitrix
Alexander, 2021-09-07 17:47:02

Why does it not update the Bitrix custom property?

There is a button

<button class="catalog__like btn shadow-none w-auto bg-transparent favorites" role="button" data-item="319"></button>


when you click it, we send the data-item data to the handler

Array.from(document.getElementsByClassName('catalog__like')).forEach((button) => {
                button.addEventListener('click', (e) => {
                    e.preventDefault();
                    console.log(e.target.getAttribute('data-item'));
                    let doAction = 'add';
                    addFavorite(e.target.getAttribute('data-item'), doAction);
                })
            });

            function addFavorite(id, action) {
                BX.ajax({
                    url: '<?=\CUtil::jsEscape(SITE_TEMPLATE_PATH)?>/ajax/favorities.php',
                    method: 'POST',
                    data: {"id": id, "action": action},
                    dataType: 'json',
                    async: true,
                    onsuccess: function (response) { 
                        if (result == 1) { 
                            console.log('ok')
                        }
                        if (result == 2) {
                            console.log('no')
                        }
                    },
                    onfailure: BX.delegate(function (response) {
                       
                    }, this),
                    error: function (jqXHR, textStatus, errorThrown) { // Если ошибка, то выкладываем печаль в консоль
                        console.log('Error: ' + errorThrown);
                        console.log(this.data)
                    }
                });

            }


handler

<? require($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_before.php");
//header('Content-Type: application/json');
$GLOBALS['APPLICATION']->RestartBuffer();

use Bitrix\Main\Application;
use Bitrix\Main\Web\Cookie;

$application = Application::getInstance();
$context = $application->getContext();
global $APPLICATION;

$request = \Bitrix\Main\HttpApplication::getInstance()->getContext()->getRequest();

if ($request->isPost() && isset($request['id']) && isset($request['action'])) {
    $idUser = $USER->GetID();
    $rsUser = CUser::GetByID($idUser);
    $arUser = $rsUser->Fetch();
    $arElements = $arUser['UF_FAVORITES'];  // Достаём избранное пользователя

    $arElements[] = $request['id'];
    $USER->Update($idUser, array("UF_FAVORITES" => $arElements)); // Добавляем элемент в избранное
    $result = 1;
    echo json_encode($result);
}

?>


in response it arrives that everything is OK (returns 1), but the data does not update

in the console flies

BX.debug:
(3) ['processing', ReferenceError: result is not defined
at Object.onsuccess (https://..............., {…}]
debug.js :41 console.trace
debug @ debug.js:41
emit @ event-emitter.js:537
onCustomEvent @ core-compatibility.js:324
BX.ajax.processRequestData @ core_ajax.js:500
BX.ajax.__run @ core_ajax.js :390
config.xhr.onreadystatechange @ core_ajax.js:228
XMLHttpRequest.send (async)
BX.ajax @ core_ajax.js:261
addFavorite @ ?clear_cache=Y:1825
(anonymous) @ ?clear_cache=Y:1819


what's wrong? what is he cursing?

decision.
corrected the response, made it a JSON
response
if (!in_array($request['id'], $arElements)) // Если еще нету этой позиции в избранном
    {
        $arElements[] = $request['id'];
        //$result = 1;
        $result = array("ID" => $request['id'], "RESULT" => 'ADD' );

    } else {
        $key = array_search($request['id'], $arElements); 
        unset($arElements[$key]);
        $result = array("ID" => $request['id'], "RESULT" => 'DEL' );
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kudis, 2021-09-07
@kikher

the answer `1` is not json, and you are asking for dataType: 'json', so BX swears in the console
that you can write an array only in a multiple (multiple) field
and, of course, you need to check if this id is already in the favorite

if (!in_array($arElements, $request->getPost('id'))) {
    $arElements[] = $request->getPost('id');
    $USER->Update($idUser, ['UF_FAVORITES' => $arElements]);    
}

S
scottparker, 2021-09-07
@scottparker

the error says that result is not defined (translation). olo, what's the result in response processing?

result == 1) {
   console.log('ok')
}
if (result == 2) {
   console.log('no')
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question