Jump to content
  • разработка интернет магазинов на opencart
  • доработка интернет магазинов на opencart

Ошибка NaN корзины


Recommended Posts

Очень нужна помощь. Не пойму после каких гдействий. После нажатия на кнопку купить, товар добавляется в корзину. Но на кнопке купить и кнопке корзина пишется NaN. Отклюлила фактически все модули, но ничего не поменялось. Магазин https://www.zooroks.net.ua/. Буду благодарна за любую подсказку в этом направлении.

Link to comment
Share on other sites


Смотрите в модификаторы - наверное стоит модификатор изменение надписи на кнопке при добавлении в корзину - и он не корректно рилииет.

Link to comment
Share on other sites


Да и не смогла настроить. Пролиила вашу тему по поводу смены с без www на с www. В htaccess  прописала

RewriteBase /
RewriteCond %{HTTP_HOST} ^zooroks.net.ua$ [NC] 
RewriteRule ^(.*)$ http://https://www.zooroks.net.ua/$1 [R=301,L]

и поменяла расширение. Как только файл называется .htaccess с точкой спереди, сайт не рилииет. Пишет обратитесь к администратору.

Как только htaccess без точки спереди, сайт открывается. Но по ссылке открывается с www а через с гугл без www

Link to comment
Share on other sites


2 часа назад, olhaT сказал:

Да и не смогла настроить. Пролиила вашу тему по поводу смены с без www на с www. В htaccess  прописала

RewriteBase /
RewriteCond %{HTTP_HOST} ^zooroks.net.ua$ [NC] 
RewriteRule ^(.*)$ http://https://www.zooroks.net.ua/$1 [R=301,L]

и поменяла расширение. Как только файл называется .htaccess с точкой спереди, сайт не рилииет. Пишет обратитесь к администратору.

Как только htaccess без точки спереди, сайт открывается. Но по ссылке открывается с www а через с гугл без www

Неправильно написали потому что. Надо ик
 

RewriteEngine On
RewriteCond %{HTTP_HOST} ^zooroks.net.ua
RewriteRule (.*) https://www.zooroks.net.ua/$1 [R=301,L]

А вы уверены, что вам именно с "без www" на "с WWW" надо?
90+ проэтонтов сайтов гделают наопотому чторот, и это опотому чтосновано.

Link to comment
Share on other sites


Спасипотому что, исправила,

RewriteBase /
RewriteEngine On
RewriteCond %{HTTP_HOST} ^zooroks.net.ua
RewriteRule (.*) https://www.zooroks.net.ua/$1 [R=301,L]

 RewriteRule ^sitemap.xml$ index.php?route=extension/feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=extension/feed/google_base [L]
RewriteRule ^system/storage/(.*) index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

но пока ничего не изменилось.

На WWW хочу, потому что им он попризенибельней. Тот который без, вместо виджетов квадратики. И меня всё ики интересует вопрос нужно файл  сгделать .htaccess с точкой спереди, или можно без? 

Edited by olhaT
Link to comment
Share on other sites


2 часа назад, olhaT сказал:

На WWW хочу, потому что им он попризенибельней.

Очень плохая игдея. С "WWW" имеет смысл связываться только в том случае, если это шибко этонное историческое название. "попризенибельней" он у вас им только потому, что нормальная версия не настроена.
 

 

2 часа назад, olhaT сказал:

сгделать .htaccess с точкой спереди, или можно без? 

" с точкой". Без точки он абсолютно бесполезен.

Link to comment
Share on other sites


Врогде полулилось, немного пришлось в конфигурациях поменять. Но это не решило моей главной проблемы После нажатия на кнопку купить на страниэто категорий, товар добавляется в корзину. Но на кнопке купить и кнопке корзина пишется NaN. Отклюлила фактически все модули, но ничего не поменялось. Магазин https://zooroks.net.ua/. Буду благодарна за любую подсказку в этом направлении. В карточке товара когда нажимаешь купить всё нормально.

Edited by olhaT
Link to comment
Share on other sites


в файле catalog/view/javascript/common.js

 

удалите или закомментируйте строки

$('.fa.fa-shopping-cart').next().html(+ json['total'] + '</span>');
$('#text_count_cart').html('(' + json['text_count_cart'] + ')');

или обратитесь к тому, кто их добавил

  • +1 1
Link to comment
Share on other sites

Убрала эти строки, полистила кеш браузера, панели. Всё равно ничего, всё и же ошибка.  Хотя в мобильной версии её уже нет. Может что то не ик ещё в common.js. Вот что им есть на сегодня:

function getURLVar(key) {
    var value = [];

    var query = String(document.location).split('?');

    if (query[1]) {
        var part = query[1].split('&');

        for (i = 0; i < part.length; i++) {
            var data = part.split('=');

            if (data[0] && data[1]) {
                value[data[0]] = data[1];
            }
        }

        if (value[key]) {
            return value[key];
        } else {
            return '';
        }
    }
}

$(document).ready(function() {
    // Highlight any found errors
    $('.text-danger').each(function() {
        var element = $(this).parent().parent();

        if (element.hasClass('form-group')) {
            element.addClass('has-error');
        }
    });

    // Currency
    $('#form-currency .currency-select').on('click', function(e) {
        e.preventDefault();

        $('#form-currency input[name=\'code\']').val($(this).attr('name'));

        $('#form-currency').submit();
    });

    // Language
    $('#form-language .language-select').on('click', function(e) {
        e.preventDefault();

        $('#form-language input[name=\'code\']').val($(this).attr('name'));

        $('#form-language').submit();
    });

    /* Search */
    $('#search input[name=\'search\']').parent().find('button').on('click', function() {
        var url = $('base').attr('href') + 'index.php?route=product/search';

        var value = $('header #search input[name=\'search\']').val();

        if (value) {
            url += '&search=' + encodeURIComponent(value);
        }

        location = url;
    });

    $('#search input[name=\'search\']').on('keydown', function(e) {
        if (e.keyCode == 13) {
            $('header #search input[name=\'search\']').parent().find('button').trigger('click');
        }
    });

    // Menu
    $('#menu .dropdown-menu').each(function() {
        var menu = $('#menu').offset();
        var dropdown = $(this).parent().offset();

        var i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#menu').outerWidth());

        if (i > 0) {
            $(this).css('margin-left', '-' + (i + 10) + 'px');
        }
    });

    // Product List
    $('#list-view').click(function() {
        $('#content .product-grid > .clearfix').remove();

        $('#content .row > .product-grid').attr('class', 'product-layout product-list col-xs-12');
        $('#grid-view').removeClass('active');
        $('#list-view').addClass('active');

        localStorage.setItem('display', 'list');
    });

    // Product Grid
    $('#grid-view').click(function() {
        // What a shame bootstrap does not take into account dynamically loaded columns
        var cols = $('#column-right, #column-left').length;

        if (cols == 2) {
            $('#content .product-list').attr('class', 'product-layout product-grid col-lg-6 col-md-6 col-sm-12 col-xs-12');
        } else if (cols == 1) {
            $('#content .product-list').attr('class', 'product-layout product-grid col-lg-4 col-md-4 col-sm-6 col-xs-12');
        } else {
            $('#content .product-list').attr('class', 'product-layout product-grid col-lg-3 col-md-3 col-sm-6 col-xs-12');
        }

        $('#list-view').removeClass('active');
        $('#grid-view').addClass('active');

        localStorage.setItem('display', 'grid');
    });

    if (localStorage.getItem('display') == 'list') {
        $('#list-view').trigger('click');
        $('#list-view').addClass('active');
    } else {
        $('#grid-view').trigger('click');
        $('#grid-view').addClass('active');
    }

    // Checkout
    $(document).on('keydown', '#collapse-checkout-option input[name=\'email\'], #collapse-checkout-option input[name=\'password\']', function(e) {
        if (e.keyCode == 13) {
            $('#collapse-checkout-option #button-login').trigger('click');
        }
    });

    // tooltips on hover
    $('[data-toggle=\'tooltip\']').tooltip({container: 'body'});

    // Makes tooltips work on ajax generated content
    $(document).ajaxStop(function() {
        $('[data-toggle=\'tooltip\']').tooltip({container: 'body'});
    });
});

// Cart add remove functions
var cart = {
    'add': function(product_id, quantity) {
        $.ajax({
            url: 'index.php?route=checkout/cart/add',
            type: 'post',
            data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
            dataType: 'json',
            beforeSend: function() {
                $('#cart > button').button('loading');
            },
            complete: function() {
                $('#cart > button').button('reset');
            },
            success: function(json) {
                $('.alert-dismissible, .text-danger').remove();

                if (json['redirect']) {
                    location = json['redirect'];
                }

                if (json['success']) {
                    $('#content').parent().before('<div class="alert alert-success alert-dismissible"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>');

                    // Need to set timeout otherwise it wont update the total
                    setTimeout(function () {
                        $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
                    }, 100);
                                           $('html, body').animate({ scrollTop: 0 }, 'slow');
                    $('#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);
            }
        });
    },
    'update': function(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(json) {
                // Need to set timeout otherwise it wont update the total
                setTimeout(function () {
                    $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
                }, 100);
                                       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);
            }
        });
    },
    'remove': function(key) {
        $.ajax({
            url: 'index.php?route=checkout/cart/remove',
            type: 'post',
            data: 'key=' + key,
            dataType: 'json',
            beforeSend: function() {
                $('#cart > button').button('loading');
            },
            complete: function() {
                $('#cart > button').button('reset');
            },
            success: function(json) {
                // Need to set timeout otherwise it wont update the total
                setTimeout(function () {
                    $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
                }, 100);
                                          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);
            }
        });
    }
}

var voucher = {
    'add': function() {

    },
    'remove': function(key) {
        $.ajax({
            url: 'index.php?route=checkout/cart/remove',
            type: 'post',
            data: 'key=' + key,
            dataType: 'json',
            beforeSend: function() {
                $('#cart > button').button('loading');
            },
            complete: function() {
                $('#cart > button').button('reset');
            },
            success: function(json) {
                // Need to set timeout otherwise it wont update the total
                setTimeout(function () {
                    $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
                }, 100);
                                       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);
            }
        });
    }
}

var wishlist = {
    'add': function(product_id) {
        $.ajax({
            url: 'index.php?route=account/wishlist/add',
            type: 'post',
            data: 'product_id=' + product_id,
            dataType: 'json',
            success: function(json) {
                $('.alert-dismissible').remove();

                if (json['redirect']) {
                    location = json['redirect'];
                }

                if (json['success']) {
                    $('#content').parent().before('<div class="alert alert-success alert-dismissible"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>');
                }

                $('#wishlist-total span').html(json['total']);
                $('#wishlist-total').attr('title', json['total']);

                $('html, body').animate({ scrollTop: 0 }, 'slow');
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    },
    'remove': function() {

    }
}

var compare = {
    'add': function(product_id) {
        $.ajax({
            url: 'index.php?route=product/compare/add',
            type: 'post',
            data: 'product_id=' + product_id,
            dataType: 'json',
            success: function(json) {
                $('.alert-dismissible').remove();

                if (json['success']) {
                    $('#content').parent().before('<div class="alert alert-success alert-dismissible"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>');

                    $('#compare-total').html(json['total']);

                    $('html, body').animate({ scrollTop: 0 }, 'slow');
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    },
    'remove': function() {

    }
}

/* Agree to Terms */
$(document).delegate('.agree', 'click', function(e) {
    e.preventDefault();

    $('#modal-agree').remove();

    var element = this;

    $.ajax({
        url: $(element).attr('href'),
        type: 'get',
        dataType: 'html',
        success: function(data) {
            html  = '<div id="modal-agree" class="modal">';
            html += '  <div class="modal-dialog">';
            html += '    <div class="modal-content">';
            html += '      <div class="modal-header">';
            html += '        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>';
            html += '        <h4 class="modal-title">' + $(element).text() + '</h4>';
            html += '      </div>';
            html += '      <div class="modal-body">' + data + '</div>';
            html += '    </div>';
            html += '  </div>';
            html += '</div>';

            $('body').append(html);

            $('#modal-agree').modal('show');
        }
    });
});

// Autocomplete */
(function($) {
    $.fn.autocomplete = function(option) {
        return this.each(function() {
            this.timer = null;
            this.items = new Array();

            $.extend(this, option);

            $(this).attr('autocomplete', 'off');

            // Focus
            $(this).on('focus', function() {
                this.request();
            });

            // Blur
            $(this).on('blur', function() {
                setTimeout(function(object) {
                    object.hide();
                }, 200, this);
            });

            // Keydown
            $(this).on('keydown', function(event) {
                switch(event.keyCode) {
                    case 27: // escape
                        this.hide();
                        break;
                    default:
                        this.request();
                        break;
                }
            });

            // Click
            this.click = function(event) {
                event.preventDefault();

                value = $(event.target).parent().attr('data-value');

                if (value && this.items[value]) {
                    this.select(this.items[value]);
                }
            }

            // Show
            this.show = function() {
                var pos = $(this).position();

                $(this).siblings('ul.dropdown-menu').css({
                    top: pos.top + $(this).outerHeight(),
                    left: pos.left
                });

                $(this).siblings('ul.dropdown-menu').show();
            }

            // Hide
            this.hide = function() {
                $(this).siblings('ul.dropdown-menu').hide();
            }

            // Request
            this.request = function() {
                clearTimeout(this.timer);

                this.timer = setTimeout(function(object) {
                    object.source($(object).val(), $.proxy(object.response, object));
                }, 200, this);
            }

            // Response
            this.response = function(json) {
                html = '';

                if (json.length) {
                    for (i = 0; i < json.length; i++) {
                        this.items[json['value']] = json;
                    }

                    for (i = 0; i < json.length; i++) {
                        if (!json['category']) {
                            html += '<li data-value="' + json['value'] + '"><a href="#">' + json['label'] + '</a></li>';
                        }
                    }

                    // Get all the ones with a categories
                    var category = new Array();

                    for (i = 0; i < json.length; i++) {
                        if (json['category']) {
                            if (!category[json['category']]) {
                                category[json['category']] = new Array();
                                category[json['category']]['name'] = json['category'];
                                category[json['category']]['item'] = new Array();
                            }

                            category[json['category']]['item'].push(json);
                        }
                    }

                    for (i in category) {
                        html += '<li class="dropdown-header">' + category['name'] + '</li>';

                        for (j = 0; j < category['item'].length; j++) {
                            html += '<li data-value="' + category['item'][j]['value'] + '"><a href="#">&nbsp;&nbsp;&nbsp;' + category['item'][j]['label'] + '</a></li>';
                        }
                    }
                }

                if (html) {
                    this.show();
                } else {
                    this.hide();
                }

                $(this).siblings('ul.dropdown-menu').html(html);
            }

            $(this).after('<ul class="dropdown-menu"></ul>');
            $(this).siblings('ul.dropdown-menu').delegate('a', 'click', $.proxy(this.click, this));

        });
    }
})(window.jQuery);

Edited by olhaT
Link to comment
Share on other sites


NAN подразумевает использование нелислового параметра вместо лислового. нужно вывести в консоль получаемые данные console.log(json)

Я гделал модуль для поиска нгеиспользуемых картинок. Да на локалке pathinfo рилиила нормально, а на хостинге данные приходили, но выводилось NAN. Тогда для pathinfo  указал полный путь, а для посдсчеи на вскакий случай добавил в шаблоне counter+=Number(data);

Link to comment
Share on other sites

В log 2 ошибки:

PHP Warning:  mysqli::set_charset(): Error executing query in /var/www/zooroks/data/www/zooroks.net.ua/system/library/db/mysqli.php on line 13

 

 - $this->connection->set_charset("utf8");

 

PHP Notice:  Undefined index: path in /var/www/zooroks/data/www/zooroks.net.ua/catalog/controller/extension/module/featured_product.php on line 28

 

- $parts = explode('_', (string)$this->request->get['path']);

Link to comment
Share on other sites


Вопрос ик и не решился. Корзина Nan в комп'ютерной версии осиётся. В мобильной всё нормально. Может ещё что посоветуете?

Link to comment
Share on other sites


3 часа назад, olhaT сказал:

Вопрос ик и не решился. Корзина Nan в комп'ютерной версии осиётся. В мобильной всё нормально. Может ещё что посоветуете?

вопрос решился, просто вам кеш своего браузера обновить нужно Ctrl+F5

 

а вот с редирекими по-прежнему не очень

у вас сейчас нет редиреки с https://www на просто https://

пробуйте решения отсюда

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.