Magento 2 Instantsearch ajax cart issue

Hi, I’m having some trouble with getting instantsearch results to use the ajax add to cart.

Basically the add-to-cart just works like ‘normal’ reloading the page.

I added a data-mage-init=’{“catalogAddToCart”:{}}’ attribute to the hit form and it works when on a catalog page or reloading the current page with query, but any new item forms generated just show the attribute within the form element instead of replacing it and attaching the event to the element.

How do I go about getting the ajax event attached to the dynamic content?

I’ve seen a few old similar questions but no answers, just abandoned threads.

Magento 2.3.4
Algolia Extension 3.0…2

Hi @jalals,

Thanks for posting here! For catalogAddToCart to work on hits that are loaded in by pagination or infiniteHits, you will need to re-initialize mage again to apply the callback to the element. We were able to develop a working snippet to add catalogAddToCart to our hits results, which you can see below:

algolia.registerHook('beforeInstantsearchStart', function(search, bundle) {
	search.on('render', function(e) {

		var addToCartForm = document.querySelectorAll("form[data-role='tocart-form']");
		addToCartForm.forEach(function(elem) {
			elem.setAttribute('data-mage-init', JSON.stringify({'catalogAddToCart': {}}));
		});

		jQuery.mage.init();

	});

	return search;
});

Magento recommends to trigger it’s ‘contentUpdated’ event to reinit but all that event does is fire mage.apply() and this jQuery event isn’t always reliable. Try the above and let us know if it helps you out! Thanks!

Haha! Triggering contentUpdated was how I got it working before seeing your response; which was a pain because I had to put it logically way after the content gets created which wasn’t making sense. But I’m familiar with unreliable Magento events so this looked better, and as I sat down to test it my contentUpdate solution started failing LOL.

Anyway, I have implemented it your way and it’s working, reliably hopefully. Cheers!