Обновление блока по Ajax

День добрый коллеги, возникла трудность, с функцией “Добавить в избранное”, в чём заключается суть проблемы.

Нажимаю добавить в избранное

Сердечко в верху должно загореться розовым цветом и рядом должно появится количество товара в избранном

Вот так выглядит мой код

image

https://www.cs-cart.ru/docs/4.4.x/developer_guide/core/front-end/ajax.html

снизу написано про обновление блоков
у вас нет класса cm-ajax и наличия атрибута data-ca-target-id в котором должен быть wishlist

или вы клик по ссылке обрабатываете скриптом?

У меня стоит обработчик событий по ссылке “Добавить в избранное”

и что он делает?

Пока ничего :grinning: мне вот и интересно как мне обновлять конкретно этот блок

сделать запрос через $.ceAjax() и в result_ids указать ваш блок

Для того, чтобы рендерились доп. блоки (кроме главного содержимого) еще требуется класс cm-ajax-full-render

То-есть по клику должна отрабатывать данная функция верно?

да, выше я давал ссылку, где можно чуть поподробнее почитать

Доброго времени суток!
Подскажите пожалуйста, всё делаю вроде по документации, но блок не обновляется!
Код блока:

{assign var="wish_count" value=""|fn_wishlist_get_count}
<a class="header__favorites cm-reload" href="{"wishlist.view"|fn_url}" rel="nofollow" id="wish_list_buttons">{if $wish_count > 0}
        <span class="count" id="wish_count_span">{$wish_count}</span>{/if}
<!--wish_list_buttons--></a>

Код кнопки:

{include file="addons/wishlist/views/wishlist/components/add_to_wishlist_product.tpl"
wishlist_but_id="button_wishlist_`$obj_prefix``$product.product_id`"
wishlist_but_name="dispatch[wishlist.add..`$product.product_id`]"
wishlist_but_role="text"
but_target_id="wish_list_buttons"
}

Код формы (код со страницы):

<form action="<здесь адрес сайта, просто убрал>" method="post" name="product_form_189" enctype="multipart/form-data" class="product-purchase__buttons cm-disable-empty-files cm-ajax cm-ajax-full-render cm-ajax-status-middle cm-processed-form">
	<input type="hidden" name="result_ids" value="cart_status*,wish_list*,checkout*,account_info*">
	<input type="hidden" name="redirect_url" value="index.php?dispatch=products.view&amp;product_id=189">
	<input type="hidden" name="product_data[189][product_id]" value="189">
	<a class="ty-btn cm-ajax product-purchase__favourite ty-add-to-wish cm-submit text-button " id="button_wishlist_189" data-ca-dispatch="dispatch[wishlist.add..189]" data-ca-target-id="wish_list_buttons"></a>
</form>

Добавление в избранное происходит, а вот сам блок, не изменияется.

1 лайк

В браузере в консоли разработчика посмотрите, правильно ли отправляется запрос и какой на него получаете ответ

Запрос:

{
	"result_ids": "cart_status*,wish_list*,checkout*,account_info*",
	"redirect_url": "index.php?dispatch=products.view&product_id=189",
	"product_data[189][product_id]": "189",
	"full_render": "Y",
	"is_ajax": "1",
	"dispatch[wishlist.add..189]": "",
	"security_hash": ""
}

Ответ:

{
	"current_url": "https://<здесь адрес сайта>/elektronika/foto-video/obektivy/af-s-14-24mm-nikkor-f-2.8g-ed/",
	"html": {
		"cart_status_1496": "\r\n                \r\n\r\n                \r\n                \n\r\n                ",
		"cart_status_1497": "\r\n                        \r\n\r\n                \r\n                        \n\r\n                        ",
		"wish_list_buttons": "        <span class=\"count\" id=\"wish_count_span\">1</span>",
		"account_info_1494": "\n                \n                    <a href=\"/profiles-update/\" rel=\"nofollow\" class=\"top-panel__user__icon\"><img src=\"/design/themes/my_theme/media/images/icons/user.svg\" alt=\"\"></a>\n                    <a href=\"#login-modal\" data-toggle=\"modal\" class=\"top-panel__user\" rel=\"nofollow\">Войти</a>\n\n\n                \n            "
	},
	"title": "AF-S 14-24mm NIKKOR f/2.8G ED Nikon",
	"notifications": {
		"01117bcfa87dff7ed54d9e54564e3883": {
			"type": "I",
			"title": "Товар добавлен в список отложенных товаров",
			"message": "<div class=\"ty-product-notification__body cm-notification-max-height\">\n                        \n            <div class=\"ty-product-notification__item clearfix\">\n                <span class=\"ty-no-image\" style=\"height: 50px; width: 50px; \"><i class=\"ty-no-image__icon ty-icon-image\" title=\"Нет изображения\"></i></span>\n\n                <div class=\"ty-product-notification__content clearfix\">\n                    <a href=\"https://<здесь адрес сайта>/elektronika/foto-video/obektivy/af-s-14-24mm-nikkor-f-2.8g-ed/\" class=\"ty-product-notification__product-name\">AF-S 14-24mm NIKKOR f/2.8G ED</a>\n                                            <div class=\"ty-product-notification__price\">\n                                                            <span class=\"none\">1</span>&nbsp;x&nbsp;<bdi><span id=\"sec_price_2456969798\" class=\"none\">150.00</span>&nbsp;<span class=\"none\"><span class=\"ty-rub\">Р</span></span></bdi>\n                                                    </div>\n                                                        </div>\n            </div>\n            \n\n            \n\n</div><div class=\"ty-product-notification__buttons clearfix\">    <div class=\"ty-float-right\">\n            \n \n\n    <a href=\"https://itmation.space/wishlist/\"  class=\"ty-btn ty-btn__secondary \" >Просмотреть список отложенных товаров</a>\n\n    </div>\n</div>",
			"message_state": "I",
			"new": true,
			"extra": "",
			"init_message": false
		}
	}
}

На сколько я понимаю wish_list_buttons есть в ответе с внутренним содержимым, но блок не обновляется

Да, потому что этого айдишника нет в result_ids

Гляньте, может блок wish_list_buttons на странице дублируется и обновляется только первый

А как его туда добавить? И в этом ли проблема? Если я меняю wish_list_buttons на wish_list, а последней в result_ids есть, то блок всё равно не обновляется.

О, вроде догнал! В common/product_data.tpl:
<input type="hidden" name="result_ids" value="cart_status*,wish_list*,checkout*,account_info*,wish_list_buttons" />

3 лайка

Ещё вопрос, а кто знает, можно ли со своего JS дёрнуть перезагрузку определённого блока после выполнения своего кода?

В общем нашёл, вот так:

$.ceAjax(‘request’, fn_url(’<url и параметр>’ + <значение параметра из переменной>), {
result_ids: ‘<id который надо обновить>’
});

2 лайка