Shopify: Add to cart with AJAX instead of redirect

If you want your users to stay on the same page instead of redirected, this is easily achievable.

The first step is to check if you have the Shopify API wrapper on your website.
To do so:

  1. Open your shop in your browser – the user-facing part, not the admin
  2. Open your browser console – for most browsers : Right click in the page > Inspect Element > Console
  3. In this console, type this:
    Shopify.addItemFromForm
    
  4. Press Enter
  5. If you see undefined, then you don’t have it, and you’ll need to add it to your layout file. Otherwise, you’re good to go.
  6. To add it to your layout file, follow the instructions on Shopify Ajax API

Now that we’ve confirmed that you indeed have this function available, open assets/algolia_instant_search.js.liquid, and locate this code:

    // Add to cart
    instant.search.addWidget({
      init: function (opts) {
        $('.ais-hits-container').on('click', '.ais-hit--cart-button', function (e) {
          e.stopPropagation();
          var $this = $(this),
              formId = $this.attr('data-form-id');

          if (formId) {
            document.getElementById(formId).submit();
          }
        });
      }
    });

In there:

// Replace
document.getElementById(formId).submit();
// by
Shopify.addItemFromForm(formId);

Finally, save the file and reload your store to confirm that it worked!