Показать описание ответа от shopify api (cart / add.js) - PullRequest
0 голосов
/ 09 июня 2019

Я пытаюсь показывать предупреждение каждый раз, когда клиент пытается добавить количество варианта, превышающее доступное количество.Когда это происходит, я вижу ответ 422 из add.js -

{status: 422, message: "Cart Error",…}
description: "All 1 Black Basic High Waisted Briefs - black / 1 are in your cart."
message: "Cart Error"
status: 422

Мне нужно отобразить описание для клиентов, как это возможно?

Вот мой код -

 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) {
    var $form = $(this);

    //Add to cart
    $.post(shopifyAjaxAddURL, $form.serialize(), function(itemData) {
      //Enable add button
      $btn.html(theme.icons.tick + ' ' + {{ 'products.product.added_to_cart' | t | json }});
      setTimeout(function(){

      //Not added, show message
      if(typeof(data) != 'undefined' && typeof(data.status) != 'undefined') {
        var jsonRes = $.parseJSON(data.responseText);
        window.showQuickPopup(jsonRes.description, $btn);
      } else {
        //Some unknown error? Disable ajax and submit the old-fashioned way.
        $form.addClass('noAJAX');
        $form.submit();
      }
    });

Ответы [ 2 ]

0 голосов
/ 09 июня 2019

Спасибо, но это не работает.На самом деле, это полный код -

  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) {
    var $form = $(this);

    //Disable add button
    var $btn = $(this).find('[type=submit]').attr('disabled', 'disabled').addClass('confirmation');
    $btn.data('originalHtml', $btn.html()).html({{ 'products.product.adding_to_cart' | t | json }});

    //Add to cart
    $.post(shopifyAjaxAddURL, $form.serialize(), function(itemData) {
      //Enable add button
      $btn.html(theme.icons.tick + ' ' + {{ 'products.product.added_to_cart' | t | json }});
      setTimeout(function(){
        $btn.removeAttr('disabled').removeClass('confirmation').html($btn.data('originalHtml'));
      }, 4000);

      var pro_hand = $. parseJSON(itemData).handle;

      var ajax_pro_handl ='/products/'+ pro_hand +'.js';
      var pro_featured_img ='';
      $.getJSON(ajax_pro_handl, function(product) {
          pro_featured_img = product.featured_image;
      }); 
      setTimeout(function(){
        if($form.hasClass('feedback-add_in_modal')) {
          showThemeModal([
            '<div id="added-to-cart" class="theme-modal align-centre top-padded" tabindex="-1">',
            '<div class="inner">',
            '<div class="container">',
            '<div class="cart-pop-upper">',
            '<a href="#" data-modal-close><i class="fa fa-close"></i></a>',
            '<h4>Cart</h4>',
            '</div>',
            '<h4 class="pro_titl">' + $. parseJSON(itemData).product_title + '</h4>',
            '<img class="image_cartpop" src="' + pro_featured_img + '"/>',
            '<p class="pro_varint">' + $. parseJSON(itemData).variant_title + '</p>',
            /*'<p>' + {{ 'products.product.popup_was_added' | t | json }} + '</p>',
            '<p class="content-row"><a class="circled-icon" href="/cart">'+theme.icons.tick+'</a></p>',
            '<p class="links"><a href="#" data-modal-close>'+{{ 'products.product.popup_continue_shopping' | t | json }}+'</a> &bull; <a href="/cart">' + {{ 'products.product.popup_checkout' | t | json }} + '</a></p>',*/
            '<a href="/cart" class="checkout_btton">' + {{ 'products.product.popup_checkout' | t | json }} + '</a>',
            '<a href="/cart" class="pop_cart_link">View Cart</a>',
            '<a href="#" class="continue_shop" data-modal-close>'+ {{ 'products.product.popup_continue_shopping' | t | json }} +'</a>',
            '</div>',
            '</div>',
            '</div>'
          ].join(''));
        }
      }, 1000);
      //Update header summary
      $.get(shopifyAjaxStorePageURL, function(data){
        var cartSummarySelector = '#site-control .cart';
        var $newCartObj = $($.parseHTML('<div>' + data + '</div>')).find(cartSummarySelector);
        var $currCart = $(cartSummarySelector);
        $currCart.replaceWith($newCartObj);
      });
    }, 'text').error(function(data) {
      //Enable add button
      $btn.removeAttr('disabled').removeClass('confirmation').html($btn.data('originalHtml'));

      //Not added, show message
      if(typeof(data) != 'undefined' && typeof(data.status) != 'undefined') {
        var jsonRes = $.parseJSON(data.responseText);
        window.showQuickPopup(jsonRes.description, $btn);
      } else {
        //Some unknown error? Disable ajax and submit the old-fashioned way.
        $form.addClass('noAJAX');
        $form.submit();
      }
    });
    setTimeout(function(){
    jQuery('#dropdown-cart').addClass('active');
    updateDropdownCart();
    },1000);
    return false;
  });

Спасибо

0 голосов
/ 09 июня 2019

Ваш код кажется немного ошибочным.Возможное решение может быть, проверить, если статус 422 и отправить клиенту сообщение с предупреждением.

if( itemData.status === 422 ) { alert('Quantity not available in the inventory') }

Полный код может выглядеть следующим образом:

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) {
    var $form = $(this);

    //Add to cart
    $.post(shopifyAjaxAddURL, $form.serialize(), function (itemData) {
        if( itemData.status === 422 ) { alert('Quantity not available in the inventory') }
        else {
            //Enable add button
        $btn.html(theme.icons.tick + ' ' + {{ 'products.product.added_to_cart' | t | json }});
        setTimeout(function () {

            //Not added, show message
            if (typeof (data) != 'undefined' && typeof (data.status) != 'undefined') {
                var jsonRes = $.parseJSON(data.responseText);
                window.showQuickPopup(jsonRes.description, $btn);
            } else {
                //Some unknown error? Disable ajax and submit the old-fashioned way.
                $form.addClass('noAJAX');
                $form.submit();
            }
        }  
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...