Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

Enable Ajax Add To Cart Magento 2 in 3 Simple Steps

Vinh Jacker | 11-11-2024

Enable Ajax Add To Cart Magento 2 in 3 Simple Steps

Numerous inquiries revolve around Ajax and enabling Ajax add-to-cart functionality in Magento 2 for product widgets. In this article, we address common queries related to these issues. Additionally, we provide two effective methods to optimize the add-to-cart process. Follow along to gain further insights.

What Is Ajax?

AJAX, short for Asynchronous JavaScript and XML, comprises a suite of technologies for developing web applications. By integrating these technologies, web pages become more responsive. With AJAX, users can interact with a web page without waiting for it to reload entirely. Only specific elements of the page are refreshed during interactions on the website.

In traditional web applications, when users interact with the web interface, HTTP requests are sent to a web server. The server then processes the request and sends back an HTML page to the client. During this transportation via HTTP, users cannot engage with the web application.

Benefits of Ajax Add To Cart Magento 2

Default Magento only allows customers to add products to their cart while on the product page, which can be a significant limitation. This setup interrupts the shopping experience as customers have to wait for the page to reload after adding an item.

Research from Kissmetrics reveals that even a 1-second delay (or just 3 seconds of waiting) can reduce customer satisfaction by about 16%, and 40% of users abandon a website that takes more than 3 seconds to load. Therefore, if you notice a high bounce rate on your website, it’s crucial to check the page load time and optimize it accordingly.

To address this issue, you can implement Ajax Add To Cart functionality in Magento 2. Enabling Ajax for the Add to Cart button offers several benefits:

  • Decrease loading time: With no page redirection, the loading time is significantly reduced.

  • Increase dwell time: All actions can be performed on a single page, leading to longer user engagement.

  • Enhance conversion rate: Faster and smoother user experience increases customer satisfaction, thus improving the conversion rate.

  • Improve website indexing: Ajax implementation can positively impact the website’s indexing by search engines.

How to enable Ajax add to cart in Magento 2

Method 1: Programmatically

Step 1: Create a Custom module

For example, I have created a Mageplaza Catalog Module.

Step 2: Add JavaScript for AJAX Handling

Create a JavaScript file that will handle the AJAX request.

File Path:

app/code/Mageplaza/Catalog/view/frontend/web/js/ajax-add-to-cart.js

Content:

require([
    'jquery'
], function ($) {
    'use strict';


    $('body').delegate('button.action.tocart', 'click', function (e) {
        var form      = $(this).closest('form'),
            actionUrl = form.attr('action');// replace by your Url
        e.preventDefault();
        $.ajax({
            url: actionUrl + '?isajaxcard=1',
            data: form.serialize(),
            type: 'POST',
            processData: 'json',
            showLoader: true,
            success: function (res) {
                Debugger;
            // Insert your custom code
                console.log("Ajax Cart");
                console.log(res);
            }
        });
    });
});

Step 3: Require the JavaScript in Your Layout XML

Add the JavaScript file to your layout.

File Path:

app/code/Mageplaza/Catalog/view/frontend/layout/default.xml

Content:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="Mageplaza_Catalog::js/ajax-add-to-cart.js"/>
    </head>
</page>

Step 4: Clear Cache and Deploy Static Content

Run the following commands to clear the cache and deploy the static content:

bin/magento setup:upgrade
bin/magento setup:static-content:deploy -f
bin/magento cache:clean
bin/magento cache:flush

Method 2: Use a third-party extension

If you find the first way quite complicated, it’s totally normal cause it’s for experienced developers with solid coding skills. So, if you’re not familiar with them, try a third-party extension instead. These Ajax Add to Cart for Magento 2 extensions are designed to make this task much simpler.

First off, you need to install a Magento 2 Ajax Add to Cart module.


AJAX Cart

AJAX Cart for Magento 2

Speed up your shopping experience with the add-to-cart pop-up function and AJAX loading

Check it out!


AJAX supports shoppers to place their favorite products quickly without being redirected to another page and our extension enhances customer satisfaction by displaying a pop-up for product details. It allows them to choose custom item options like colour, size, quantity and instantly add to the cart.

Add to cart

Now, let’s move to the configuration!

Navigate to Stores > Configuration > Mageplaza > Quick View + Ajax Cart

Ajax cart configuration

Next, expand the AJAX Cart Configuration section and fill out the following fields

  • Enable: Choose Yes to activate Ajax cart
  • Apply for: Multi-select the pages you would like to display the popup of Ajax Cart
  • Apply for actions:
    • Add To Cart: Display the popup of Ajax Cart when customers press on Add To Cart button
    • Add To Compare: Display the popup of Ajax Cart when customers press on Add To Compare button on Quick View Popup
    • Add To Wishlist: Display the popup of Ajax Cart when customers press on Add To Wishlist button on Quick View Popup

Enable the module

  • Enable animation effect: Select Yes to use the animation function of your products. It will auto-fly into the cart after clicking the Add To Cart button.

  • Countdown time: Set the number of seconds for displaying the Ajax Cart popup

  • Show Mini Cart instead when an item is added: When the customer only adds 1 item to the cart, display the mini cart instead. If more than 1 product were added, display the Ajax popup as normal.

Enable animation effect

How To Extend Add To Cart Function Of Product Widget With Ajax

If you’re looking to enhance the functionality of the “Add to Cart” button with AJAX logic for both default category product lists and product pages, you can follow the guide below:

Step 1: Override the addtocart.phtml file located at:

app/design/frontend/vendorname/themename/Magento_Catalog/templates/product/view/addtocart.phtml 

Step 2: Update the script to set “bindSubmit” to true instead of false:

From:

<script type="text/x-magento-init"> 
{
    "#product_addtocart_form": {
        "catalogAddToCart": {
            "bindSubmit": false
        }
    }
}
</script> 

To:

<script type="text/x-magento-init"> 
{
    "#product_addtocart_form": {
        "catalogAddToCart": {
            "bindSubmit": true
        }
    }
}
</script>

Step 3: Clear the cache or flush the cache by deleting the cache and page_cache folders.

Note: Ensure that you have set “No” for After Adding a Product Redirect to Shopping Cart from Store -> Configuration -> Sales -> Checkout -> Shopping Cart.

Shopping card configuration

Utilize Third-Party Extension - Magento 2 AJAX Cart Extension

A convenient alternative to manually researching and implementing enhancements for a better shopping experience is to utilize third-party extensions. We highly recommend Magento 2 AJAX Cart Extension by Mageplaza as the fastest solution for this requirement.

Magento 2 AJAX Cart Extension empowers customers to swiftly select and add products to their shopping cart directly within an add-to-cart popup. Additionally, the Quick View feature allows users to preview items within the popup without leaving the current page, eliminating wait times and redirect hassles.

Furthermore, this extension provides exclusive functionalities like AJAX Add to Wishlist and Add to Compare. With customizable popup designs and appealing animation effects, the AJAX Add to Cart extension ensures a mobile-friendly solution that greatly enriches the shopping experience.

Pricing:

  • Standard Plan: $149 for the first year

  • Enterprise Plan: $349 for the first year

Highlight features:

  • Improve shopping experience by reduced loading time and user-friendly site

  • AJAX Add to Cart to allow customers to add items quickly and a pop-up to display product details and custom options

  • Convenient Add to WishList or Compare products features

  • Quick view pop-up supported

  • Lively animation effects with various pop-up effects and flying image effect

  • Store admins can customize pop-up design


AJAX Cart

AJAX Cart for Magento 2

Speed up your shopping experience with the add-to-cart pop-up function and AJAX loading

Check it out!


Conclusion

In this article, we not only provide information about Ajax but also guide you on how to enhance your add-to-cart button effectively. Also, we recommend the best and quickest solution to save both your time and effort. We believe that this information will prove valuable to you.

Table of content
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services