Good evening! I implement the addition of goods without rebooting. Here's what happened:

// добавление в корзину $goods_id = abs((int)$_GET['goods_id']); addtocart($goods_id); $_SESSION['total_sum'] = total_sum($_SESSION['cart']); // кол-во товара в корзине + защита от ввода несуществующего ID товара $_SESSION['total_quantity'] = 0; foreach($_SESSION['cart'] as $key => $value){ if(isset($value['price'])){ // если получена цена товара из БД - суммируем кол-во $_SESSION['total_quantity'] += $value['qty']; }else{ // иначе - удаляем такой ID из сессии (корзины) unset($_SESSION['cart'][$key]); } } redirect(); 

  /* ===Сумма заказа в корзине + атрибуты товара===*/ function total_sum($goods){ global $connection; $total_sum = 0; $str_goods = implode(',',array_keys($goods)); $query = "SELECT goods_id, name, price FROM goods WHERE goods_id IN ($str_goods)"; $res = mysqli_query($connection, $query) or die(mysqli_error()); while($row = mysqli_fetch_assoc($res)){ $_SESSION['cart'][$row['goods_id']]['name'] = $row['name']; $_SESSION['cart'][$row['goods_id']]['price'] = $row['price']; $total_sum += $_SESSION['cart'][$row['goods_id']]['qty'] * $row['price']; } return $total_sum; } /* ===Сумма заказа в корзине + атрибуты товара===*/ 

 <?php if($_SESSION['total_quantity']): ?> Товаров в корзине:<br /> <span id="bought"><?=$_SESSION['total_quantity']?></span> на сумму <span id="sum"><?=$_SESSION['total_sum']?></span> руб. <img src="<?=TEMPLATE?>images/korzinaON.png" class="korzinaON" /> <a href="#"><img src="<?=TEMPLATE?>images/oformit.png" class="oformit" alt="Оформить заказ" /></a> <?php else: ?> <span class="offK">Корзина пуста</span> <img src="<?=TEMPLATE?>images/korzinaOFF.png" class="korzinaOFF" /> <?php endif; ?> 

 /* ===Добавление в корзину=== */ function addtocart($goods_id){ if(isset($_SESSION['cart'][$goods_id])){ // если в массиве cart уже есть добавляемый товар $_SESSION['cart'][$goods_id]['qty'] += 1; return $_SESSION['cart']; }else{ // если товар кладется в корзину впервые $_SESSION['cart'][$goods_id]['qty'] = 1; return $_SESSION['cart']; } } /* ===Добавление в корзину=== */ 

Link to the price.

 <p>Цена : <span><?=$product['price']?> р.</span></p> <a class="buyitem" href="?view=addtocart&goods_id=<?=$product['goods_id']?>"><img class="addtocard-index" src="<?=TEMPLATE?>images/addcard-table.jpg" alt="Добавить в корзину" /></a> 

Here is the js:

  $(".buyitem").click(function(){ var url = $(this).attr("href"); // при клике на ссылку считываем href var regprice = /[\d]+$/; var price= $(this).closest(".product-table").find("span").text(); price = parseInt(price,10); //Считаем полное количество купленных товаров и полную цену var total_items = parseInt($("#bought").text(),10)+1; var total_price = parseInt($("#sum").text(),10)+price; //записываем то, что посчитали в соответствующие места на странице $("#bought").text(total_items); $("#sum").text(total_price); //url ссылки отправляем методом get на сервер - эффект будет такой же, как если бы пользователь перешел по ссылке $.get(url); return false; //предотвращаем переход по ссылке = перезагрузку страницы }); 

Adds to the basket without reloading, but after updating the page, all items from the basket disappear.

    1 answer 1

    Sessions are not created when you refresh the page? Check that after reboot contains $ _SESSION ['total_quantity'].

    • @Get, not generated. - DimasikYES
    • I understand correctly that the session data is deleted when the page is updated? If so, see the logic. Somewhere or close the session, or create a new one. Check if the data is written to the session. Try to test the recording and saving of any variable in the session. - Get
    • @Get, Without a script, everything works fine, only adding with updating the page. _____ @Get, the fact is that in chrome it does not work, but in the moss, say, it works, after the page is reloaded, the product remains in the basket. Why is that? - DimasikYES 10:08 pm
    • And the scripts in chrome are not cached by you, by any chance? In MSIE check, work? - Get
    • @Get, another site with the same code you open, everything is fine there. Strange. - DimasikYES