Liquid Ajax Cart

repository·main·Indexed 42 days ago

https://github.com/evgeniymukhamedjanov/liquid-ajax-cart

A tool for Shopify developers to implement AJAX-based cart updates and product form submissions using Liquid and HTML attributes, eliminating the need for custom JavaScript coding. Version 2.2.0 provides a global window.liquidAjaxCart object with API methods such as get(), add(), change(), update(), and clear() to interact with Shopify's cart endpoints.

Tokens
52.3K
Snippets
160
Records
224
Agent score
49%

What's inside Liquid Ajax Cart

  1. How Ajaxified sections work

    main

    Liquid Ajax Cart automatically reloads the HTML content of containers marked with the data-ajax-cart-section attribute whenever the Shopify cart changes.

    It leverages Shopify's Bundled section rendering to request re-rendered HTML for specific theme sections alongside Cart API responses. Because of this mechanism, the data-ajax-cart-section attribute must be applied within Shopify sections.

  2. Understand the Request state object

    main

    A Request state is a JavaScript object created for every Shopify Cart API Ajax request. It serves as a central container where Liquid Ajax Cart stores information about the request, its payload, the initiator, and the resulting response or error. You can access this object within liquid-ajax-cart:request-start and liquid-ajax-cart:request-end event handlers to inspect or modify request behavior.

    {
      "endpoint": "/cart/add.js",
      "requestBody": {"items": [{"id": 40934235668668, "quantity": 1}], "sections": "my-cart"},
      "requestType": "add",
      "info": {
        "initiator": Element {},
        "cancel": false
      },
      "responseData": {
        "ok": true,
        "status": 200,
        "body": {…}
      },
      "extraResponseData": {
        "ok": true,
        "status": 200,
        "body": {…}
      }
    }
  3. Use the .js-ajax-cart-empty CSS class to style empty carts

    main

    Liquid Ajax Cart automatically manages the .js-ajax-cart-empty CSS class on the <body> tag to help you style your store differently when the cart is empty.

    When the cart is empty, the class .js-ajax-cart-empty is added to the <body>. When items are added to the cart, this class is removed.

    Note: The documentation title refers to .js-ajax-cart-empty, but the text describes the logic for adding/removing a class based on cart state. Use this class in your CSS to hide/show elements (like

  4. Understand the Request state object

    main

    Liquid Ajax Cart tracks the state of every Shopify Cart Ajax API request using a JavaScript object called "Request state". These objects are passed as parameters to the callback functions you define when using Cart Ajax API requests functions.

    Object Structure

    A typical successful request state object contains:

    • endpoint: The URL of the request (e.g., /cart/add.js).
    • requestBody: The payload sent. It is a JSON or FormData object for POST requests, and undefined for GET requests.
    • requestType: The type of operation (e.g., add).
    • info: Additional metadata provided by the caller.
      • When using Product forms or Controls, this includes an initiator property containing the HTMLElement that triggered the request.
      • If info.cancel is set to true, the request is aborted and responseData will not be present.
    • responseData: The result of the request. The ok property is true if the HTTP status is in the 200-299 range.
    • extraResponseData: Contains data from additional requests performed by Liquid Ajax Cart to ensure the UI is synchronized (see "Extra Response Data" below).

    Handling Network Errors

    If a request fails due to network issues (e.g., internet disconnection), the responseData property will be missing. Instead, the object will contain a fetchError property containing the error message and stack trace.

    {
      "endpoint": "/cart/add.js",
      "requestBody": {"items": [{"id": 40934235668668, "quantity": 1}], "sections": "my-cart"},
      "requestType": "add",
      "info": {
        "initiator": Element {}
      },
      "responseData": {
        "ok": true, 
        "status": 200, 
        "body": {...}
      },
      "extraResponseData": {
        "ok": true, 
        "status": 200, 
        "body": {...}
      }
    }
  5. Handle successful and failed requests using `responseData` and `fetchError`

    main

    Depending on the outcome of the Shopify Cart API request, you should check different properties in the Request state:

    • Successful Requests: Check responseData. If responseData.ok is true, the request was successful (status 200–299).
    • Failed Requests (No Response): If the request failed before a response was received (e.g., due to network issues), responseData will be null. In this case, look for the fetchError property to diagnose the issue.
    • Additional Data: If Liquid Ajax Cart had to perform an extra POST /cart/update.js request (to fetch missing cart state or extra sections), the result is stored in extraResponseData.
  6. Use the .js-ajax-cart-not-empty class to style elements based on cart state

    main

    The library automatically appends the CSS class js-ajax-cart-not-empty to the <html> tag whenever the user's cart contains items. You can use this class in your CSS to conditionally show or hide elements (like a cart quantity badge) only when the cart is not empty.

    To implement this, use a CSS selector starting with html.js-ajax-cart-not-empty to target child elements.

    /* Example: Show the quantity badge only when the cart is not empty */
    html.js-ajax-cart-not-empty .header__cart-quantity {
      display: inline-block;
    }
  7. What are cart mutations and how do they work

    main

    A mutation is a custom JavaScript function that allows you to automatically add or remove items from the Shopify cart based on specific logic (e.g., promotions or cart corrections).

    How it works:

    1. You define a function that inspects the current cart state.
    2. You register this function using the mutations configuration parameter.
    3. Liquid Ajax Cart executes your function when the page loads and every time the cart changes.
    4. If your function returns an object containing a requests array, Liquid Ajax Cart performs the specified Shopify Cart API Ajax requests.

    This is useful for scenarios like:

    • Adding a free gift when a price threshold is met.
    • Removing a specific product if another product is missing.
    • Enforcing cart limits.
  8. How Shopify Cart API request queues work

    main

    All Shopify Cart API requests in liquid-ajax-cart are managed via a queuing system to prevent race conditions. Requests are grouped into sequential queues. The system processes all requests in the first queue in order; once the first queue is empty, it is removed, the second queue becomes the first, and the process repeats.

    This mechanism ensures that multiple asynchronous cart operations (like adding items or changing quantities) are executed in a predictable, serial order.

  9. Update request parameters: firstCallback, lastCallback, and important

    main

    When making requests in v2, note the following parameter name changes and behaviors:

    • Callbacks: firstComplete and lastComplete are now firstCallback and lastCallback.
    • Queue Priority: The newQueue parameter is replaced by important.
      • When important is true, the request is added to the beginning of the request queue.
      • The default value for important is false.
  10. Understand the Liquid Ajax Cart State object

    main

    The State is a JavaScript object that holds all information related to the user's cart. It is automatically updated by Liquid Ajax Cart after every successful Shopify Cart API request.

    Important: To ensure the State remains synchronized, always use the functions provided in the Cart Ajax API requests reference instead of making direct Shopify Cart API calls. Using the library's built-in methods ensures the internal state is updated correctly.

  11. How the request queue lifecycle works

    main

    Liquid Ajax Cart does not execute Shopify Cart API Ajax requests immediately. Instead, it manages them through a Queue of requests.

    When a request is initiated (e.g., via an "Add to cart" button click or a direct method call) and the queue is currently empty, the following sequence occurs:

    1. The request is added to the Queue.
    2. The liquid-ajax-cart:queue-start event is dispatched on the document.
    3. The library begins performing the request(s).