2017-12-13 11 views
2

장바구니를 작성 중입니다. 기본적으로 각 장바구니에 대한 값을 저장하기 위해 각 제품마다 item_id를 사용합니다. 새 index.php를 호출하기 때문에 장바구니에서 항목을 추가/제거 할 때마다 항상 페이지 상단으로 이동합니다.PHP 코드로 페이지를 새로 고칠 수없는 방법

스크롤 위치를 변수로 저장하고 이전 scrollPos로 이동하려고 시도했지만 작동하지 않았습니다 (#names를 호출하지 않음).

누구나 페이지를 새로 고치지 않는 방법으로이 문제를 해결할 수 있습니다.

여기에 내 코드

<?php 

session_start(); 

$page = 'index.php'; 
$con = mysqli_connect('localhost','root','0801','mystore') ; 
mysqli_select_db($con,'mystore') ; 

#for adding, removing, deleting the products from the cart 
if(isset($_GET["add"])){ //same name with cart.php?add <-- 
$_SESSION['cart_'.(int)$_GET["add"]] += 1; 
echo '<script>window.location="index.php"; window.scrollTo(0,1200);</script>'; 
} 

if(isset($_GET['remove'])){ 
    $_SESSION['cart_'.(int)$_GET['remove']] -- ; 
    header("Location: ".$page); 
} 

if(isset($_GET['delete'])){ 
    $_SESSION['cart_'.(int)$_GET['delete']] = 0 ; 
    header('Location: '.$page); 
} 

#function for displaying products 
function product(){ 
    global $con; 
    $get = mysqli_query($con, 'SELECT * FROM inventory ORDER BY id ASC'); 

    if (mysqli_num_rows($get) == 0){ 
    echo("There are no products to display"); 
    } else { 
    while ($get_row = mysqli_fetch_assoc($get)){ 
    echo '<br /><img src="images/products/'.$get_row['image'].'" width=100px;>'; 
    echo '<br>'.$get_row['name'].'<br /> &dollar;'.number_format($get_row['price'],2); 

echo '<br> <a href="cart.php?add='.$get_row['id'].'">Add To Cart</a> 
    } 
    } 
} #end of function 


# function for display cart 
function cart(){ 
    foreach ($_SESSION as $key => $value) { 
    if ($value > 0){ 
     if(substr($key, 0 , 5) =='cart_'){ 
     global $con; //DON'T FORGET TO ADD THIS!!! 
     $id = substr($key, 5, (strlen($key)-5)); //take out the string part 
     $partid = mysqli_real_escape_string($con, $id); 
     $get = mysqli_query($con,'SELECT * FROM inventory WHERE id='.(int)$partid); 

     while($get_row = mysqli_fetch_assoc($get)){ 
      $subTotal = $get_row['price'] * $value; 
      echo '<br /><img src="images/products/'.$get_row['image'].'" width=30px;>'; 
      echo $get_row['name'].' x '.$value.' @ &dollar;'.number_format($get_row['price'], 2); 
      echo ' = &dollar;'.number_format($subTotal,2); 
      echo '<a href="cart.php?remove='.$id.'"> [-] </a> <a href="cart.php?add='.$id.'">[+]</a> <a href="cart.php?delete='.$id.'"> [delete] </a><br />'; 
     } 
     } 
     $total += $subTotal; 
    } 
    } 
    if ($total ==0){ 
     echo "Your cart is empty"; 
    } else { 
     echo '<p /> TOTAL: &dollar;'.number_format($total, 2); 
    } 
} 

print_r($_SESSION); 

?> 

답변

0

추가/카트에서 항목을 제거하는 jQuery Ajax 전화를 사용하는 것을 고려한다. 이렇게하면 페이지를 새로 고침 할 필요가 없습니다.

0
당신은 다음과 같이 다음 위치를 저장 페이지가 다시로드 될 때 다시 위치로 가져 세션 스토리지를 사용할 수 있습니다

:

JQuery와 :의 사용과

$(window).scroll(function() { 
    sessionStorage.scrollTop = $(this).scrollTop(); 
}); 

$(document).ready(function() { 
    if (sessionStorage.scrollTop != "undefined") { 
    $(window).scrollTop(sessionStorage.scrollTop); 
    } 
}); 

또는 자바 스크립트 코드 쿠키와 같은 :

자바 스크립트 :

<script> 
    cookieName="page_scroll" 
    expdays=365 

    function setCookie(name, value, expires, path, domain, secure){ 
    if (!expires){expires = new Date()} 
    document.cookie = name + "=" + escape(value) + 
    ((expires == null) ? "" : "; expires=" + expires.toGMTString()) + 
    ((path == null) ? "" : "; path=" + path) + 
    ((domain == null) ? "" : "; domain=" + domain) + 
    ((secure == null) ? "" : "; secure") 
    } 

    function getCookie(name) { 
    var arg = name + "=" 
    var alen = arg.length 
    var clen = document.cookie.length 
    var i = 0 
    while (i < clen) { 
    var j = i + alen 
    if (document.cookie.substring(i, j) == arg){ 
    return getCookieVal(j) 
    } 
    i = document.cookie.indexOf(" ", i) + 1 
    if (i == 0) break 
    } 
    return null 
    } 

    function getCookieVal(offset){ 
    var endstr = document.cookie.indexOf (";", offset) 
    if (endstr == -1) 
    endstr = document.cookie.length 
    return unescape(document.cookie.substring(offset, endstr)) 
    } 

    function deleteCookie(name,path,domain){ 
    document.cookie = name + "=" + 
    ((path == null) ? "" : "; path=" + path) + 
    ((domain == null) ? "" : "; domain=" + domain) + 
    "; expires=Thu, 01-Jan-00 00:00:01 GMT" 
    } 

    function saveScroll(){ // added function 
    var expdate = new Date() 
    expdate.setTime (expdate.getTime() + (expdays*24*60*60*1000)); // expiry date 

    var x = (document.pageXOffset?document.pageXOffset:document.body.scrollLeft) 
    var y = (document.pageYOffset?document.pageYOffset:document.body.scrollTop) 
    Data=x + "_" + y 
    setCookie(cookieName,Data,expdate) 
    } 

    function loadScroll(){ // added function 
    inf=getCookie(cookieName) 
    if(!inf){return} 
    var ar = inf.split("_") 
    if(ar.length == 2){ 
    window.scrollTo(parseInt(ar[0]), parseInt(ar[1])) 
    } 
    } 
<script> 

HTML :

<body onload="loadScroll()" onunload="saveScroll()" >