You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shopify中展示cart/add.js返回的422错误描述给客户

Fixing Shopify AJAX Add-to-Cart Error Handling for 422 Responses

Looking at your existing code, there are a few key gaps preventing it from properly handling the 422 error response from Shopify's cart/add.js endpoint:

  1. No error handling setup: The original code only defines a success callback, so it never catches error responses like 422.
  2. Undefined variables: The data variable inside the setTimeout isn't passed from anywhere, so it will always be undefined.
  3. Missing default submission prevention: You aren't stopping the form from submitting normally before the AJAX request completes.
  4. Unmanaged button state: The submit button's state (disabled/enabled, text) isn't properly handled during loading or errors.

Here's the corrected code that addresses all these issues and properly displays the error description from the 422 response:

var shopifyAjaxAddURL = '/cart/add.js';
var shopifyAjaxCartURL = '/cart.js';
var shopifyAjaxStorePageURL = '/search';

$(document).on('submit', 'form[action="/cart/add"]:not(.noAJAX, .feedback-go_to_cart)', function(e) {
  // Prevent default form submission to let AJAX handle it
  e.preventDefault();
  
  var $form = $(this);
  // Target the submit button in the form to manage its state
  var $btn = $form.find('button[type="submit"], input[type="submit"]');
  
  // Disable button and show loading state
  $btn.prop('disabled', true).html(theme.icons.loading + ' ' + {{ 'products.product.adding_to_cart' | t | json }});

  // Send AJAX request to add item to cart
  $.post(shopifyAjaxAddURL, $form.serialize())
    .done(function(itemData) {
      // Success: Item added to cart
      $btn.html(theme.icons.tick + ' ' + {{ 'products.product.added_to_cart' | t | json }});
      
      // Optional: Reset button to original state after a short delay
      setTimeout(function() {
        $btn.prop('disabled', false).html({{ 'products.product.add_to_cart' | t | json }});
      }, 2000);
    })
    .fail(function(jqXHR) {
      // Re-enable button immediately on error
      $btn.prop('disabled', false);
      
      // Handle 422 validation errors (like insufficient stock)
      if (jqXHR.status === 422) {
        try {
          // Parse the error response from Shopify
          var errorResponse = JSON.parse(jqXHR.responseText);
          
          // Show the description from the error if available
          if (errorResponse.description) {
            window.showQuickPopup(errorResponse.description, $btn);
          } else {
            // Fallback to a generic error message if description is missing
            window.showQuickPopup({{ 'products.product.error_add_to_cart' | t | json }}, $btn);
          }
          
          // Reset button text to original
          $btn.html({{ 'products.product.add_to_cart' | t | json }});
        } catch (e) {
          // Handle cases where the response isn't valid JSON
          window.showQuickPopup({{ 'products.product.error_add_to_cart' | t | json }}, $btn);
          $btn.html({{ 'products.product.add_to_cart' | t | json }});
        }
      } else {
        // For non-422 errors (e.g., network issues), fall back to traditional form submission
        $form.addClass('noAJAX');
        $form.submit();
      }
    });
});

Key Changes Explained:

  • e.preventDefault(): Stops the form from submitting normally, ensuring our AJAX request runs first.
  • Button State Management: Disables the button during loading to prevent duplicate clicks, then re-enables it on success/error.
  • .done() and .fail() Callbacks: Separates success and error handling logic clearly. The .fail() callback catches all non-200 responses, including 422.
  • 422 Error Handling: Specifically checks for the 422 status code, parses the Shopify error response, and displays the description field using your existing window.showQuickPopup function.
  • Fallback Logic: Includes fallbacks for missing error descriptions, invalid JSON, and non-422 errors (falling back to traditional submission when needed).

内容的提问来源于stack exchange,提问作者Or Ben-Yossef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:25:14