Magento 2.4.4-p2 | Search Page | Add-To-Cart | Reloads | Ajax Failure

Dear Support,
I have applied the following settings under Magento → Admin → Algolia Search

  • Enable Instant Search Results Page => Yes
  • Add to Cart => Yes

At the front-end, the search page behavior is surprising. Click on the “Add-To-Cart” button the page reloads and success message appears.
The Ajax functionality doesn’t work at all the time.

Steps to reproduce:

  • Magento mini-search, search any term

  • On the search page, click add-to-cart.

  • On the search page, input and search any term in the “Algolia mini-search”.

  • After results, click add-to-cart.

Please check the attached screenshots.

Thanks,


Finally, after many hours of efforts I’m able to resolve it.

  1. Override, js file into custom theme: /vendor/algolia/algoliasearch-magento-2/view/frontend/web/instantsearch.js

Update the function startInstantSearch as follows:

 function startInstantSearch() {
                if (isStarted === true) {
                    return;
                }

                /*
                * custom work,
                * issue: many times ajax add-to-cart is not working,
                * specifically, after searching by algolia search field on the search page,
                * */
                algolia.registerHook('beforeInstantsearchStart', function (search, algoliaBundle) {
                    search.on('render', function (e) {
                        var addToCartForm = document.querySelectorAll("form[data-role='tocart-form']");
                        addToCartForm.forEach(function (elem) {
                            var form = elem;
                            $(form).on("submit", function (e) {
                                e.preventDefault();
                            });
                        });
                    });
                    console.log('algolia, stop add-to-cart');

                    return search;
                });

                search = algolia.triggerHooks('beforeInstantsearchStart', search, algoliaBundle);
                search.start();
                search = algolia.triggerHooks('afterInstantsearchStart', search, algoliaBundle);

                isStarted = true;
            }

I utilized, registerHook “beforeInstantsearchStart” to stop default Algolia add-to-cart processing.

Then I trigger the add-to-cart processing in my way.

  1. Open file: /vendor/algolia/algoliasearch-magento 2/view/frontend/templates/instant/hit.phtml

Search and remove attribute “itemscope”.

Thanks,