Количество товаров в сплывающей корзине opencart 3

Тема в разделе "Общие вопросы", создана пользователем Kylun-Serg, 23 мар 2023.

  1. Kylun-Serg

    Kylun-Serg Новичок

    Сообщения:
    6
    Симпатии:
    0
    Подскажите как исправить ошибку. Хочу добавить возможность изменять количество товаров после добавления в корзину.

    [​IMG]

    В файл cart.twig добавлена разметка:

    Код:
    <td>
        <div class="cart_quantity_button">
          
            <a style="font-size:20px; cursor:pointer" class="cart_quantity_down" data-key="{{ product.cart_id }}">-</a>
    
            <input class="cart_quantity_input" type="text" name="quantity" value="{{ product.quantity }}" autocomplete="off" size="2" readonly>
    
            <a style="font-size:20px; cursor:pointer" class="cart_quantity_up" data-key="{{ product.cart_id }}">+</a>
          
        </div>
    </td>
    И в файл common.js добавлено функцию и слушатели:

    Код:
    function updateCart(key, quantity) {
    
        $.ajax({
            url: 'index.php?route=checkout/cart/edit',
            type: 'post',
            data: 'key=' + key + '&quantity=' + (typeof (quantity) != 'undefined' ? quantity : 1),
            dataType: 'json',
            beforeSend: function () {
                $('#cart > button').button('loading');
            },
            complete: function () {
                $('#cart > button').button('reset');
    
            },
            success: function (data) {
    
                // Обновление количества товаров в корзине
                $('#cart-total').html(data['total']);
    
                // Обновление содержимого корзины
                if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
                    location = 'index.php?route=checkout/cart';
                } else {
    
                    $('#cart > ul').load('index.php?route=common/cart/info ul li');
                }
            },
            error: function (jqXHR, exception) {
                if (jqXHR.status === 0) {
                    alert('Not connect. Verify Network.');
                } else if (jqXHR.status == 404) {
                    alert('Requested page not found (404).');
                } else if (jqXHR.status == 500) {
                    alert('Internal Server Error (500).');
                } else if (exception === 'parsererror') {
                    alert('Requested JSON parse failed.');
                } else if (exception === 'timeout') {
                    alert('Time out error.');
                } else if (exception === 'abort') {
                    alert('Ajax request aborted.');
                } else {
                    alert('Uncaught Error. ' + jqXHR.responseText);
                }
            }
        });
    }
    
    $('.cart_quantity_up').on('click', function () {
        var key = $(this).data('key');
        var quantity = $(this).parent().find('.cart_quantity_input').val();
        quantity++;
        $(this).parent().find('.cart_quantity_input').val(quantity);
    
        updateCart(key, quantity);
    });
    
    $('.cart_quantity_down').on('click', function () {
        var key = $(this).data('key');
        var quantity = $(this).parent().find('.cart_quantity_input').val();
        if (quantity > 1) {
            quantity--;
            $(this).parent().find('.cart_quantity_input').val(quantity);
            updateCart(key, quantity);
        }
    });
    При нажатии на +/- срабатывает событие, количество увеличивается/уменьшается и вызывается функция updateCart() которая должна обновить содержимое корзины. Но метод success не выполняется, так как получаю ошибку "parsererror".

    [​IMG]
     
  2. Ravilr

    Ravilr Специалист

    Сообщения:
    3.863
    Симпатии:
    1.059
    Для начала вопрос, а стандартный cart.update чем не угодил в качестве примера или использования?
     
  3. Kylun-Serg

    Kylun-Serg Новичок

    Сообщения:
    6
    Симпатии:
    0
    Этот код в точности как у метода cart.update
     
  4. Ravilr

    Ravilr Специалист

    Сообщения:
    3.863
    Симпатии:
    1.059
    А Вы проверяли, что приходит у Вас в key, quantity
    Может вместо значений, передаете объект?
     
  5. Kylun-Serg

    Kylun-Serg Новичок

    Сообщения:
    6
    Симпатии:
    0
    нет, там 2 числа
     
  6. Ravilr

    Ravilr Специалист

    Сообщения:
    3.863
    Симпатии:
    1.059
    Ошибка парсинга у Вас из за того, что в ответ приходит ошибка. из за того, что в контроллер передает данные не в том формате. Подправил, чтобы видно было формат

    Код:
    function updateCart(key, quantity) {
    
        $.ajax({
            url: 'index.php?route=checkout/cart/editj',
            type: 'post',
            data: 'quantity['+ key +']=' + (typeof (quantity) != 'undefined' ? quantity : 1),
            dataType: 'json',
            beforeSend: function () {  },
            complete: function () { },
            success: function (json) {
    
                // Обновление количества товаров в корзине
                $('#cart-total').html(json['total']);
    
                // Обновление содержимого корзины
                if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
                    location = 'index.php?route=checkout/cart';
                } else {
    
                    //$('#cart > ul').load('index.php?route=common/cart/info ul li');
                }
            },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                }
        });
    }
    Далее, в контроллере нет возможности вернуть нужные данные в json , поэтому и там меняем, а точнее напишем свое, как то так.

    \catalog\controller\checkout\cart.php

    PHP:
        public function editj() {
            
    $this->load->language('checkout/cart');

            
    $json = array();

            
    // Update
            
    if (!empty($this->request->post['quantity'])) {
                foreach (
    $this->request->post['quantity'] as $key => $value) {
                    
    $this->cart->update($key$value);
                }

                
    $this->session->data['success'] = $this->language->get('text_remove');

                unset(
    $this->session->data['shipping_method']);
                unset(
    $this->session->data['shipping_methods']);
                unset(
    $this->session->data['payment_method']);
                unset(
    $this->session->data['payment_methods']);
                unset(
    $this->session->data['reward']);

                
    // Totals
                
    $this->load->model('setting/extension');

                
    $totals = array();
                
    $taxes $this->cart->getTaxes();
                
    $total 0;

                
    // Because __call can not keep var references so we put them into an array.             
                
    $total_data = array(
                    
    'totals' => &$totals,
                    
    'taxes'  => &$taxes,
                    
    'total'  => &$total
                
    );

                
    // Display prices
                
    if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                    
    $sort_order = array();

                    
    $results $this->model_setting_extension->getExtensions('total');

                    foreach (
    $results as $key => $value) {
                        
    $sort_order[$key] = $this->config->get('total_' $value['code'] . '_sort_order');
                    }

                    
    array_multisort($sort_orderSORT_ASC$results);

                    foreach (
    $results as $result) {
                        if (
    $this->config->get('total_' $result['code'] . '_status')) {
                            
    $this->load->model('extension/total/' $result['code']);

                            
    // We have to put the totals in an array so that they pass by reference.
                            
    $this->{'model_extension_total_' $result['code']}->getTotal($total_data);
                        }
                    }

                    
    $sort_order = array();

                    foreach (
    $totals as $key => $value) {
                        
    $sort_order[$key] = $value['sort_order'];
                    }

                    
    array_multisort($sort_orderSORT_ASC$totals);
                }

                
    $json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total$this->session->data['currency']));
            
            }

            
    $this->response->addHeader('Content-Type: application/json');
            
    $this->response->setOutput(json_encode($json));
        }
     
    Kylun-Serg нравится это.
  7. Kylun-Serg

    Kylun-Serg Новичок

    Сообщения:
    6
    Симпатии:
    0
    Спасибо большое.