简体   繁体   中英

how can i add products to the cart wihtout refreshing the product list?

I made a simple shopping cart function but I have 2 problems now. 1 is my product list is so big and my cart and my product list are in same page. When visitor click on add button its take too long time to reload how can make it work without refreshing the product page I mean add the product to cart without the refreshing the product page? And my second problem is I want a product's stock update function how can I make a product update function form that cart function? Here is my code

<?php 
session_start();

$page = 'producst.php';


// my add function
if (isset($_GET['add'])) {
    $quantity = mysql_query('SELECT id, quantity FROM products WHERE id='.mysql_real_escape_string((int)$_GET['add']));
    while ($quantity_row = mysql_fetch_assoc($quantity)) {
        if ($quantity_row['quantity']!=$_SESSION['cart_'.(int)$_GET['add']]){
            $_SESSION['cart_'.(int)$_GET['add']]+='1';
        }
    }
    header('Location: '.$page); 
}


// my product list function
function products(){
    $result = '';
    $get = mysql_query('SELECT id, name, description, price FROM products WHERE quantity > 0 ORDER BY id DESC');
    if (mysql_num_rows($get)==0) {
    }else{
         while ($get_row = mysql_fetch_assoc($get)) {
             $result .= '<p>'.$get_row['name'].'<br />'.$get_row['description'].'<br />&pound;'.$get_row['price'].' <a href="cart.php?add='.$get_row['id'].'">add</a></p>';
             }
    }
    return $result;
}

// my cart function
function cart() {
    $result = '';
    foreach($_SESSION as $name => $value){
        if ($value>0) {
            if (substr($name, 0, 5)=='cart_') {
                $id = substr($name, 5, (strlen($name)-5));
                $get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
                while ($get_row = mysql_fetch_assoc($get)) {
                    $sub = $get_row['price']*$value;
                    $result .= $get_row['name'].' x '.$value.' @ &pound;'.$get_row['price'].' = &pound;'.$sub.'<br />';
                }
            }
        }
    }
    return $result;
}
?>

You'd have to use JavaScript and AJAX to send requests to your PHP script without reloading the page. PHP runs on your server, while JavaScript runs on and interacts with the browser.

Do some research about AJAX (look at the jQuery framework if you'd like).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM