SiteDream Posted April 13, 2016 Report Share Posted April 13, 2016 Добрый день, при добавление товара в корзину он улетает, всё отлично, но когда я нажимаю на корзину там пусто.С чем это связано? <?PHP /** * Simpla CMS * * @copyright 2009 Denis Pikusov * @link http://simp.la * @author Denis Pikusov * * Корзина покупок * Этот класс использует шаблон cart.tpl * */ require_once('View.php'); class CartView extends View { ////////////////////////////////////////// // Изменения товаров в корзине ////////////////////////////////////////// public function __construct() { parent::__construct(); // Если передан id варианта, добавим его в корзину if($variant_id = $this->request->get('variant', 'integer')) { $this->cart->add_item($variant_id, $this->request->get('amount', 'integer')); header('location: '.$this->config->root_url.'/cart/'); } // Удаление товара из корзины if($delete_variant_id = intval($this->request->get('delete_variant'))) { $this->cart->delete_item($delete_variant_id); if(!isset($_POST['submit_order']) || $_POST['submit_order']!=1) header('location: '.$this->config->root_url.'/cart/'); } // Если нажали оформить заказ if(isset($_POST['checkout'])) { $order = new stdClass; /*order-on-one-page*/ $order->payment_method_id=$this->request->post('payment_method_id', 'integer'); /*/order-on-one-page*/ $order->delivery_id = $this->request->post('delivery_id', 'integer'); $order->name = $this->request->post('name'); $order->email = $this->request->post('email'); $order->address = $this->request->post('address'); $order->phone = $this->request->post('phone'); $order->comment = $this->request->post('comment'); $order->ip = $_SERVER['REMOTE_ADDR']; $this->design->assign('delivery_id', $order->delivery_id); $this->design->assign('name', $order->name); $this->design->assign('email', $order->email); $this->design->assign('phone', $order->phone); $this->design->assign('address', $order->address); $captcha_code = $this->request->post('captcha_code', 'string'); // Скидка $cart = $this->cart->get_cart(); $order->discount = $cart->discount; if($cart->coupon) { $order->coupon_discount = $cart->coupon_discount; $order->coupon_code = $cart->coupon->code; } // if(!empty($this->user->id)) $order->user_id = $this->user->id; if(empty($order->name)) { $this->design->assign('error', 'empty_name'); } elseif(empty($order->email)) { $this->design->assign('error', 'empty_email'); } elseif($_SESSION['captcha_code'] != $captcha_code || empty($captcha_code)) { $this->design->assign('error', 'captcha'); } else { /*cms-mailing*/ $news = $this->request->post('is_send_news'); if ($news) { $query = $this->db->placehold('select id from __mailing where email=?', $order->email); $this->db->query($query); if($this->db->num_rows() < 1) { $query = $this->db->placehold('insert into __mailing(`email`)VALUES(?)', $order->email); $this->db->query($query); } } /*/cms-mailing*/ // Добавляем заказ в базу $order_id = $this->orders->add_order($order); $_SESSION['order_id'] = $order_id; // Если использовали купон, увеличим количество его использований if($cart->coupon) $this->coupons->update_coupon($cart->coupon->id, array('usages'=>$cart->coupon->usages+1)); // Добавляем товары к заказу foreach($this->request->post('amounts') as $variant_id=>$amount) { $this->orders->add_purchase(array('order_id'=>$order_id, 'variant_id'=>intval($variant_id), 'amount'=>intval($amount))); } $order = $this->orders->get_order($order_id); // Стоимость доставки $delivery = $this->delivery->get_delivery($order->delivery_id); if(!empty($delivery) && $delivery->free_from > $order->total_price) { /*install-delivery*/ if ($delivery->is_install_price) { $cart = $this->cart->get_cart(); $price = 0; foreach($cart->purchases as $item) { $price += (($item->variant->install_price > 0.00) ? $item->variant->install_price : $delivery->price) * $item->amount; } $delivery->price = $price; } /*/install-delivery*/ $this->orders->update_order($order->id, array('delivery_price'=>$delivery->price, 'separate_delivery'=>$delivery->separate_payment)); } // Отправляем письмо пользователю $this->notify->email_order_user($order->id); // Отправляем письмо администратору $this->notify->email_order_admin($order->id); // Очищаем корзину (сессию) $this->cart->empty_cart(); // Перенаправляем на страницу заказа header('Location: '.$this->config->root_url.'/order/'.$order->url); } } else { // Если нам запостили amounts, обновляем их if($amounts = $this->request->post('amounts')) { foreach($amounts as $variant_id=>$amount) { $this->cart->update_item($variant_id, $amount); } $coupon_code = trim($this->request->post('coupon_code', 'string')); if(empty($coupon_code)) { $this->cart->apply_coupon(''); header('location: '.$this->config->root_url.'/cart/'); } else { $coupon = $this->coupons->get_coupon((string)$coupon_code); if(empty($coupon) || !$coupon->valid) { $this->cart->apply_coupon($coupon_code); $this->design->assign('coupon_error', 'invalid'); } else { $this->cart->apply_coupon($coupon_code); header('location: '.$this->config->root_url.'/cart/'); } } } } } ////////////////////////////////////////// // Основная функция ////////////////////////////////////////// function fetch() { // Способы доставки $deliveries = $this->delivery->get_deliveries(array('enabled'=>1)); /*install-delivery*/ foreach($deliveries as $delivery) { if ($delivery->is_install_price) { $cart = $this->cart->get_cart(); $price = 0; foreach($cart->purchases as $item) { $price += (($item->variant->install_price > 0.00) ? $item->variant->install_price : $delivery->price) * $item->amount; } $delivery->price = $price; break; } } /*/install-delivery*/ /*order-on-one-page*/ foreach($deliveries as $delivery) $delivery->payment_methods = $this->payment->get_payment_methods(array('delivery_id'=>$delivery->id, 'enabled'=>1)); $this->design->assign('all_currencies', $this->money->get_currencies()); /*/order-on-one-page*/ $this->design->assign('deliveries', $deliveries); // Данные пользователя if($this->user) { $last_order = $this->orders->get_orders(array('user_id'=>$this->user->id, 'limit'=>1)); $last_order = reset($last_order); if($last_order) { $this->design->assign('name', $last_order->name); $this->design->assign('email', $last_order->email); $this->design->assign('phone', $last_order->phone); $this->design->assign('address', $last_order->address); } else { $this->design->assign('name', $this->user->name); $this->design->assign('email', $this->user->email); } } // Если существуют валидные купоны, нужно вывести инпут для купона if($this->coupons->count_coupons(array('valid'=>1))>0) $this->design->assign('coupon_request', true); // Выводим корзину return $this->design->fetch('cart.tpl'); } } {* Шаблон корзины *} {$meta_title = "Корзина" scope=parent} <div class="row"> <section class="breadcrumb lower twelve columns"> <h1 class="title_page upper"> {if $cart->purchases}В корзине {$cart->total_products} {$cart->total_products|plural:'товар':'товаров':'товара'} {else}Корзина пуста{/if} </h1> ← <a rel="nofollow" href="javascript:history.back();">Вернуться</a> / <a href="./">Главная</a> </section> </div> {if $cart->purchases} <form method="post" name="cart"> {* Список покупок *} <table id="purchases"> <div class="row"> <div class="twelve columns"> <hr class="line_separe_black bgsprite"> </div> </div> {*{if $cart->purchases} <form method="post" name="cart" class="cart custom"> <div class="row thead hide-for-small"> <div class="one columns"></div> <div class="three columns">товар</div> <div class="two columns">размер</div> <div class="two columns">цена</div> <div class="one columns">количество</div> <div class="two columns">итого</div> <div class="one columns"></div> </div> {/if}*} {foreach from=$cart->purchases item=purchase} <div class="row item"> {* Изображение товара *} <div class="one columns mobile-one"> {* Изображение товара *} {$image = $purchase->product->images|first} {if $image} <img src="{$image->filename|resize:70:91}" alt="{$purchase->product->name|escape}"> {/if} </div> <div class="three columns mobile-two"> <div class="name br1pxdotted"> {* Название товара *} <a href="./products/{$purchase->product->url}/">{$purchase->product->name|escape}</a> <div class="brand">{$purchase->product->brand|escape}</div> </div> </div> <div class="two columns hide-for-small"> <div class="size br1pxdotted"> {$purchase->variant->name|escape} </div> </div> <div class="two columns hide-for-small"> <div class="price br1pxdotted"> {* Цена за единицу *} {($purchase->variant->price)|convert} {$currency->sign} </div> </div> <div class="one columns hide-for-small"> <div class="amount br1pxdotted"> {* Количество *} <select name="amounts[{$purchase->variant->id}]" onchange="document.cart.submit();" class="expand" id="customDropdown"> {section name=amounts start=1 loop=$purchase->variant->stock+1 step=1} <option value="{$smarty.section.amounts.index}" {if $purchase->amount==$smarty.section.amounts.index}selected{/if}>{$smarty.section.amounts.index} </option> {/section} </select> </div> </div> <div class="two columns hide-for-small"> <div class="t_price br1pxdotted"> {* Цена *} <b>{($purchase->variant->price*$purchase->amount)|convert} {$currency->sign}</b> </div> </div> <div class="one columns mobile-one"> <div class="remove"> {* Удалить из корзины *} <a class="bgsprite" href="./cart/remove/{$purchase->variant->id}/">удалить</a> </div> </div> </div> {/foreach} {if $user->discount} <tr> <th class="image"></th> <th class="name">скидка</th> <th class="price"></th> <th class="amount"></th> <th class="price"> {$user->discount} % </th> <th class="remove"></th> </tr> {/if} {if $coupon_request} {*<tr class="coupon"> <th class="image"></th> <th class="name" colspan="3">Код купона или подарочного ваучера {if $coupon_error} <div class="message_error"> {if $coupon_error == 'invalid'}Купон недействителен{/if} </div> {/if} <div> <input type="text" name="coupon_code" value="{$cart->coupon->code|escape}" class="coupon_code"> </div> {if $cart->coupon->min_order_price>0}(купон {$cart->coupon->code|escape} действует для заказов от {$cart->coupon->min_order_price|convert} {$currency->sign}){/if} <div> <input type="button" name="apply_coupon" value="Применить купон" onclick="document.cart.submit();"> </div> </th> <th class="price"> {if $cart->coupon_discount>0} −{$cart->coupon_discount|convert} {$currency->sign} {/if} </th> <th class="remove"></th> </tr>*} {literal} <script> $("input[name='coupon_code']").keypress(function(event){ if(event.keyCode == 13){ $("input[name='name']").attr('data-format', ''); $("input[name='email']").attr('data-format', ''); document.cart.submit(); } }); </script> {/literal} {/if} <tr> <th class="image"></th> <th class="name"></th> <th class="price" colspan="4"> Итого {$cart->total_price|convert} {$currency->sign} </th> </tr> </table> {* Доставка *} {if $deliveries} <fieldset> <legend>1/ Выберите способ доставки</legend> {* Доставка *} {foreach $deliveries as $delivery} <div class="row mobile-two"> <div class="one columns"> <input type="radio" name="delivery_id" value="{$delivery->id}" {if $delivery_id==$delivery->id}checked{elseif $delivery@first}checked{/if} id="deliveries_{$delivery->id}"> </div> <div class="eleven columns description" style="left: -70px;"> <label for="deliveries_{$delivery->id}"> {$delivery->name} {if $cart->total_price < $delivery->free_from && $delivery->price>0} (+{$delivery->price|convert} {$currency->sign}) {elseif $cart->total_price >= $delivery->free_from} (бесплатно) {/if} </label> <span class="hide-for-small">{$delivery->description}</p> </div> </div> {/foreach} </fieldset> {/if} <div class="five columns"> <fieldset> <legend>2/ Введите данные получателя</legend> {if $error} <div class="message_error"> {if $error == 'empty_name'}Введите имя{/if} {if $error == 'empty_email'}Введите email{/if} {if $error == 'captcha'}Капча введена неверно{/if} </div> {/if} <label>Имя, фамилия</label> <input name="name" type="text" value="{$name|escape}" data-format=".+" data-notice="Введите имя"/> <label>Email</label> <input name="email" type="text" value="{$email|escape}" data-format="email" data-notice="Введите email" /> <label>Телефон</label> <input name="phone" type="text" value="{$phone|escape}" /> <label>Адрес доставки</label> <input name="address" type="text" value="{$address|escape}"/> <label>Комментарий к заказу</label> <textarea name="comment" id="order_comment">{$comment|escape}</textarea> <div class="captcha"><img src="captcha/image.php?{math equation='rand(10,10000)'}" alt='captcha'/></div> <input class="input_captcha" id="comment_captcha" type="text" name="captcha_code" value="" data-format="\d\d\d\d" data-notice="Введите капчу"/> <div class="row"> <div class="twelve columns"> <p class="text-center"><input type="submit" name="checkout" class="button large radius" value="3/ оформить заказ →" style=" background: #000; "></p> <p class="text-center labelinfo"><br>и перейти к оплате</p> </div> </div> </fieldset> <form class="form register_form" method="post"> <div class="form cart_form"> <!--emailing--> <label>Подписаться на новости</label> <input type="checkbox" name="is_send_news" /> <!--/emailing--> {else} В корзине нет товаров {/if} Quote Link to post Share on other sites
DaVinci Posted April 13, 2016 Report Share Posted April 13, 2016 1. Корзину переписывали, дополняли? 2. В информере меняется количество товаров в корзине? 3. Открывали ли сайт в другом браузере?4. Достаточно ли места на хостинге? 5. Работают ли сессии? Quote Link to post Share on other sites
SiteDream Posted April 13, 2016 Author Report Share Posted April 13, 2016 (edited) 1. Корзину переписывали, дополняли? 2. В информере меняется количество товаров в корзине? 3. Открывали ли сайт в другом браузере? 4. Достаточно ли места на хостинге? 5. Работают ли сессии?1)Стоит подписка на новости галочка2)Да меняется3)Да в 3 браузерах4) Использование дискового пространства1,97 GB / 3,91 GB Потребление виртуальной памяти23,6 / 1024 MB Потребление физической памяти19 / 1024 MB 5)Где это проверить? Edited April 13, 2016 by SiteDream Quote Link to post Share on other sites
DaVinci Posted April 13, 2016 Report Share Posted April 13, 2016 а если обновить страницу с карточки товара информер обнуляется или показывает что товары в корзине есть? Quote Link to post Share on other sites
SiteDream Posted April 13, 2016 Author Report Share Posted April 13, 2016 а если обновить страницу с карточки товара информер обнуляется или показывает что товары в корзине есть?В общем, вот корзинаЯ нажимаю добавить товар хоть 20 всё работаетНо когда нажму обновить сайт в браузере, эти цифры пропадают как на 1 скрине, Но когда обратно нажму добавить товар, эти цифры появляются дальше. А когда нажму на корзину там пишется В корзине нет товаров Quote Link to post Share on other sites
trainracing Posted April 13, 2016 Report Share Posted April 13, 2016 В общем, вот корзинаScreenshot.pngЯ нажимаю добавить товар хоть 20 всё работаетScreenshot1.pngНо когда нажму обновить сайт в браузере, эти цифры пропадают как на 1 скрине, Но когда обратно нажму добавить товар, эти цифры появляются дальше. А когда нажму на корзину там пишется В корзине нет товаровПопробуйте переключить на стандартный шаблон и посмотреть, работает ли на нем. Из этого вам будет понятно имеется ли проблема на хостинге Quote Link to post Share on other sites
SiteDream Posted April 13, 2016 Author Report Share Posted April 13, 2016 Попробуйте переключить на стандартный шаблон и посмотреть, работает ли на нем. Из этого вам будет понятно имеется ли проблема на хостингеНе работает на дефолте Quote Link to post Share on other sites
star Posted April 13, 2016 Report Share Posted April 13, 2016 (edited) 5)Где это проверить?Screenshot.pngнапример так <?PHP if (!session_start()) die('Не работает сессия'); else echo ('работает сессия'); ?> Edited April 13, 2016 by star Quote Link to post Share on other sites
SiteDream Posted April 13, 2016 Author Report Share Posted April 13, 2016 хост сказал Судя по всему у вас проблема хранения данных в сессии , хотя сессии я вижу они создаются Quote Link to post Share on other sites
mishanya Posted April 13, 2016 Report Share Posted April 13, 2016 хост сказал Судя по всему у вас проблема хранения данных в сессии , хотя сессии я вижу они создаются покажите еще api/Cart.php Quote Link to post Share on other sites
SiteDream Posted April 13, 2016 Author Report Share Posted April 13, 2016 покажите еще api/Cart.php <?php /** * Simpla CMS * * @copyright 2011 Denis Pikusov * @link http://simplacms.ru * @author Denis Pikusov * */ require_once('Simpla.php'); class Cart extends Simpla { /* * * Функция возвращает корзину * */ public function get_cart() { $cart = new stdClass(); $cart->purchases = array(); $cart->total_price = 0; $cart->total_products = 0; $cart->coupon = null; $cart->discount = 0; $cart->coupon_discount = 0; // Берем из сессии список variant_id=>amount if(!empty($_SESSION['shopping_cart'])) { $session_items = $_SESSION['shopping_cart']; $variants = $this->variants->get_variants(array('id'=>array_keys($session_items))); if(!empty($variants)) { foreach($variants as $variant) { $items[$variant->id] = new stdClass(); $items[$variant->id]->variant = $variant; $items[$variant->id]->amount = $session_items[$variant->id]; $products_ids[] = $variant->product_id; } $products = array(); foreach($this->products->get_products(array('id'=>$products_ids, 'limit' => count($products_ids))) as $p) $products[$p->id]=$p; $images = $this->products->get_images(array('product_id'=>$products_ids)); foreach($images as $image) $products[$image->product_id]->images[$image->id] = $image; foreach($items as $variant_id=>$item) { $purchase = null; if(!empty($products[$item->variant->product_id])) { $purchase = new stdClass(); $purchase->product = $products[$item->variant->product_id]; $purchase->variant = $item->variant; $purchase->amount = $item->amount; $cart->purchases[] = $purchase; $cart->total_price += $item->variant->price*$item->amount; $cart->total_products += $item->amount; } } // Пользовательская скидка $cart->discount = 0; if(isset($_SESSION['user_id']) && $user = $this->users->get_user(intval($_SESSION['user_id']))) $cart->discount = $user->discount; $cart->total_price *= (100-$cart->discount)/100; // Скидка по купону if(isset($_SESSION['coupon_code'])) { $cart->coupon = $this->coupons->get_coupon($_SESSION['coupon_code']); if($cart->coupon && $cart->coupon->valid && $cart->total_price>=$cart->coupon->min_order_price) { if($cart->coupon->type=='absolute') { // Абсолютная скидка не более суммы заказа $cart->coupon_discount = $cart->total_price>$cart->coupon->value?$cart->coupon->value:$cart->total_price; $cart->total_price = max(0, $cart->total_price-$cart->coupon->value); } else { $cart->coupon_discount = $cart->total_price * ($cart->coupon->value)/100; $cart->total_price = $cart->total_price-$cart->coupon_discount; } } else { unset($_SESSION['coupon_code']); } } } } return $cart; } /* * * Добавление варианта товара в корзину * */ public function add_item($variant_id, $amount = 1) { $amount = max(1, $amount); if(isset($_SESSION['shopping_cart'][$variant_id])) $amount = max(1, $amount+$_SESSION['shopping_cart'][$variant_id]); // Выберем товар из базы, заодно убедившись в его существовании $variant = $this->variants->get_variant($variant_id); // Если товар существует, добавим его в корзину if(!empty($variant) && ($variant->stock>0) ) { // Не дадим больше чем на складе $amount = min($amount, $variant->stock); $_SESSION['shopping_cart'][$variant_id] = intval($amount); } } /* * * Обновление количества товара * */ public function update_item($variant_id, $amount = 1) { $amount = max(1, $amount); // Выберем товар из базы, заодно убедившись в его существовании $variant = $this->variants->get_variant($variant_id); // Если товар существует, добавим его в корзину if(!empty($variant) && $variant->stock>0) { // Не дадим больше чем на складе $amount = min($amount, $variant->stock); $_SESSION['shopping_cart'][$variant_id] = intval($amount); } } /* * * Удаление товара из корзины * */ public function delete_item($variant_id) { unset($_SESSION['shopping_cart'][$variant_id]); } /* * * Очистка корзины * */ public function empty_cart() { unset($_SESSION['shopping_cart']); unset($_SESSION['coupon_code']); } /* * * Применить купон * */ public function apply_coupon($coupon_code) { $coupon = $this->coupons->get_coupon((string)$coupon_code); if($coupon && $coupon->valid) { $_SESSION['coupon_code'] = $coupon->code; } else { unset($_SESSION['coupon_code']); } } } Quote Link to post Share on other sites
mishanya Posted April 13, 2016 Report Share Posted April 13, 2016 вы бы просто прикрепили а не километры заливали, но не суть. у меня ваши файлы работают, значит либо проблема в каком-то другом файле, либо что-то с кодировкой еще, либо сервер хреновый. надо уже на сервере смотреть Quote Link to post Share on other sites
SiteDream Posted April 13, 2016 Author Report Share Posted April 13, 2016 вы бы просто прикрепили а не километры заливали, но не суть. у меня ваши файлы работают, значит либо проблема в каком-то другом файле, либо что-то с кодировкой еще, либо сервер хреновый. надо уже на сервере смотретьЭто жесть, api, view, js, simpla поменял папки на стандарт всё ранво такой косяк и на дефол шаблоне Quote Link to post Share on other sites
SiteDream Posted April 13, 2016 Author Report Share Posted April 13, 2016 вы бы просто прикрепили а не километры заливали, но не суть. у меня ваши файлы работают, значит либо проблема в каком-то другом файле, либо что-то с кодировкой еще, либо сервер хреновый. надо уже на сервере смотретьОшибки включил Notice: Undefined property: stdClass::$is_install_price in /home/m12014/public_html/at/view/CartView.php on line 198 Quote Link to post Share on other sites
mishanya Posted April 14, 2016 Report Share Posted April 14, 2016 Ошибки включил Notice: Undefined property: stdClass::$is_install_price in /home/m12014/public_html/at/view/CartView.php on line 198это не ошибка а предупреждение и он не должен влиять на получение корзины Quote Link to post Share on other sites
SiteDream Posted April 14, 2016 Author Report Share Posted April 14, 2016 это не ошибка а предупреждение и он не должен влиять на получение корзиныБаза mysql может влиять на это? Quote Link to post Share on other sites
mishanya Posted April 14, 2016 Report Share Posted April 14, 2016 База mysql может влиять на это? нет, корзина пишется в сессию а не в базу. тут надо на сессии смотреть. попробуйте на другом хостинге запустить этот же сайт или на локальном пк Quote Link to post Share on other sites
SiteDream Posted April 14, 2016 Author Report Share Posted April 14, 2016 нет, корзина пишется в сессию а не в базу. тут надо на сессии смотреть. попробуйте на другом хостинге запустить этот же сайт или на локальном пкТоже самое Quote Link to post Share on other sites
SiteDream Posted April 14, 2016 Author Report Share Posted April 14, 2016 В общем в index.php session_start(); небыло из за этого не пахала корзина Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.