Cart update with ajax and php

I'm learning how can i use ajax, jquery and php to update a cart. I found this code and i'm trying to adapt it, but without success. The problem is that i can't add any item to the cart and after a search on google still don't understand where is the problem.

<script>
   $(document).ready(function(){    
    $(".form-item").submit(function(e){
        var form_data = $(this).serialize();
        var button_content = $(this).find('button[type=submit]');
        button_content.html('Adding...'); //Loading button text 

        $.ajax({ //make ajax request to cart_process.php
            url: "../../cart_process.php",
            type: "POST",
            dataType:"json", //expect json value from server
            data: form_data
        }).done(function(data){ //on Ajax success
            $("#cart-info").html(data.items); //total items in cart-info element
            button_content.html('Add to Cart'); //reset button text to original text
            alert("Item added to Cart!"); //alert user
            if($(".shopping-cart-box").css("display") == "block"){ //if cart box is still visible
                $(".cart-box").trigger( "click" ); //trigger click to update the cart box.
            }
        })
        e.preventDefault();
    });

//Show Items in Cart
$( ".cart-box").click(function(e) { //when user clicks on cart box
    e.preventDefault(); 
    $(".shopping-cart-box").fadeIn(); //display cart box
    $("#shopping-cart-results").html('<img src="images/ajax-loader.gif">'); //show loading image
    $("#shopping-cart-results" ).load( "../../cart_process.php", {"load_cart":"1"}); //Make ajax request using jQuery Load() & update results
});

//Close Cart
$( ".close-shopping-cart-box").click(function(e){ //user click on cart    box close link
    e.preventDefault(); 
    $(".shopping-cart-box").fadeOut(); //close cart-box
});

//Remove items from cart
$("#shopping-cart-results").on('click', 'a.remove-item', function(e) {
    e.preventDefault(); 
    var pcode = $(this).attr("data-code"); //get product code
    $(this).parent().fadeOut(); //remove item element from box
    $.getJSON( "../../cart_process.php", {"remove_code":pcode} ,  function(data){ //get Item count from Server
        $("#cart-info").html(data.items); //update Item count in cart-   info
        $(".cart-box").trigger( "click" ); //trigger click on cart-box   to update the items list
    });
});

});

prodotto.php Here i have the description of the product, the form to select quantity and the button to add the product to the cart

<?php
require_once("../inc/config.php");
require_once(ROOT_PATH . "inc/database.php");
require_once(ROOT_PATH . "prodotti/prod.php");
require_once(ROOT_PATH . "login/user.php");
sec_session_start();




 if(isset($_GET['sku'])) {
 $sku = intval($_GET['sku']);
 $prodotto = get_product_single($sku);
 }

 if(empty($prodotto)){
 header("Location:" . BASE_URL);
 exit();
 }



 include(ROOT_PATH . "inc/header.php"); 
 include(ROOT_PATH . "inc/side-menu.php");  

try{ 
$results = $db->prepare("SELECT * from prodotti WHERE sku = ?");
$results->bindParam(1,$sku);
$results->execute();

$prodotto = $results->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo "Nessun prodotto da visualizzare con queste caratteristiche";
die();
} 
?>
   <div id="content" class="large-8 columns round-all" role="main" itemscope itemtype="http://schema.org/LocalBusiness" style="background-color:#eee;padding-right:1em;">
    <div class="row" style="padding-right:1em;">

      <?php
      $categoria = get_category($prodotto['categoria']);

      ?>
      <nav class="breadcrumbs" role="menubar" aria-label="breadcrumbs" itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
        <li role="menuitem"><a href="<?php echo BASE_URL;?>categorie/index.php?sku=<?php echo $categoria['id']; ?>" itemprop="url"><span itemprop=”title”><?php echo $categoria['nome'];?></span></a></li>
        <li role="menuitem" class="current"><span itemprop=”title”><?php echo $prodotto['nome'];?></span></li>
      </nav>
      <a href="#" class="cart-box" id="cart-info" title="View Cart">
 <?php 
if(isset($_SESSION["products"])){
 echo count($_SESSION["products"]); 
}else{
echo 0; 
}
?>

<div class="shopping-cart-box">
<a href="#" class="close-shopping-cart-box" >Close</a>
 <h3>Your Shopping Cart</h3>
 <div id="shopping-cart-results">
 </div>
 </div>
      <?php

          echo '<li role="menuitem" style="list-style-type:none;">


                  <div class="large-12 columns" style="background-color:#fff;" itemscope itemtype="http://schema.org/Product">
                    <div class="small-1 medium-2 large-4 columns" style="border:10px #eee solid">
                    <span itemprop ="image"><img src="' . BASE_URL . 'img/profumo-hugo-boss.jpg";/></span>
                    </div>
                    <div class="small-1 medium-4 large-8 columns" >
                    <span itemprop="name"><h3>'.$prodotto['nome'].'</h3></span>
                    <h6>Codice: ' . $prodotto['sku'] . '</h6>
                    <span itemprop="price"><h6>Prezzo: <span style="color:red;font-weight:bold;";>' . $prodotto['prezzo'] . '<span itemprop="priceCurrency">€</span></span></h6></span>
                    <span itemprop="description"><p>'.$prodotto['descrizione'].'</p></span>';?>

                    <form class="form-item">
                               <div class="small-1 medium-2 large-4">
                                    <label for="quantita">Quantità</label>

                                <select name="quantita" id="quantita">
                                  <option value="1">1 </option>
                                  <option value="2">2 </option>
                                  <option value="3">3 </option>
                                  <option value="4">4 </option>
                                  <option value="5">5 </option>
                                  <option value="6">6 </option>
                                  <option value="7">7 </option>
                                  <option value="8">8 </option>
                                  <option value="9">9 </option>
                                  <option value="10">10 </option>
                                </select> 
                              </div>
                              <div class="small-1 medium-2 large-4">
                                <input type="hidden" name="sku" value="<?php echo $prodotto['sku'];?>"/>
                                <input type="hidden" name="id_sessione" value="<?php echo $_SESSION['id'];?>"/>
                                <input type="submit" value="Aggiungi al carrello" class="button" name="submit">

                                </div>
                                </form>


                    </div>
                  </div>

                </li>
    </div>
   </div>
  </div>
</div>

Cart_process.php

include_once("../inc/config.php");
sec_session_start(); 

############# add products to session #########################
if(isset($_POST["sku"]))
{
foreach($_POST as $key => $value){
    $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);      //create a new product array 
}

//we need to get product name and price from database.
$statement = $db->prepare("SELECT nome, sku FROM prodotti WHERE sku=?    LIMIT 1");
$statement->bindParam(1, $new_product['sku']);
$statement->execute();

$prodotto = $statement-fetch(PDO::FETCH_ASSOC);


while($prodotto){ 
    $new_product["nome"] = $prodotto['nome']; //fetch product name from database
    $new_product["sku"] = $prodotto['sku'];  //fetch product sku from database

    if(isset($_SESSION["products"])){  //if session var already exist
        if(isset($_SESSION["products"][$new_product['sku']])) //check item exist in products array
        {
            unset($_SESSION["products"][$new_product['sku']]); //unset old item
        }           
    }

    $_SESSION["products"][$new_product['sku']] = $new_product;  //update products with new item array   
}

$total_items = count($_SESSION["products"]); //count total items
die(json_encode(array('items'=>$total_items))); //output json 

}

################## list products in cart ###################
if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
{

if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){    //if we have session variable
    $cart_box = '<ul class="cart-products-loaded">';
    $total = 0;
    foreach($_SESSION["products"] as $product){ //loop though items and prepare html content

        //set variables to use them in HTML content below
        $product_name = $product["nome"]; 
        /*$product_price = $product["product_price"];
        */$product_code = $product["sku"];/*
        $product_qty = $product["product_qty"];
        $product_color = $product["product_color"];
        $product_size = $product["product_size"];
        */
        $cart_box .=  "<li> $product_name <a href=\"#\" class=\"remove-item\" data-code=\"$product_code\">&times;</a></li>";
        //$subtotal = ($product_price * $product_qty);
        //$total = ($total + $subtotal);
    }
    $cart_box .= "</ul>";
    //$cart_box .= '<div class="cart-products-total">Total : '.$currency.sprintf("%01.2f",$total).' <u><a href="view_cart.php" title="Review Cart and Check-Out">Check-out</a></u></div>';
    die($cart_box); //exit and output content
    }else{
    die("Your Cart is empty"); //we have empty cart
   }
  }

  ################# remove item from shopping cart ################
  if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
  {
  $product_code   = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); //get the product code to remove

if(isset($_SESSION["products"][$product_code]))
{
    unset($_SESSION["products"][$product_code]);
}

$total_items = count($_SESSION["products"]);
die(json_encode(array('items'=>$total_items)));
}

Answers


Moving forward from our discussion in the comments, I will be posting a functional behavior of the code with a sample data from database since you wanted it to be dynamic.

As this was for learning purpose I've had used prepared statements with some msql_. (both in different files) Please note that msql_ is deprecated and I urge not to use it.

Before starting, I assume you have all the required files downloaded and saved in the correct path and used either method (filesystem/storing directly to database) for the images, I have however used the filesystem behavior. Now, there are three tables used from the database:

1) category table with columns as follow:

  • cat_id
  • cat_name

2) item table which has the columns as follow:

  • item_id
  • item_name
  • item_quantity
  • item_size
  • cat_id (FK from category table)
  • item_color

3) products_list table with following columns:

  • id (AI, PK)
  • product_name
  • product_desc
  • product_code
  • product_image
  • item_id (FK from item table)
  • product_price
  • product_discount

Now, Starting with the very first page.

index.php

<?php
session_start(); //start session
include("config.php"); //include config file
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>

<script>
$(document).ready(function(){   
        $(".form-item").submit(function(e){
            var form_data = $(this).serialize();
            var button_content = $(this).find('button[type=submit]');
            button_content.html('Adding...');  

            $.ajax({ 
                url: "cart_process.php",
                type: "POST",
                dataType:"json", 
                data: form_data
            }).done(function(data){ 
                $("#cart-info").html(data.items); 
                button_content.html('Add to Cart'); 
                alert("Item added to Cart!"); 
                if($(".shopping-cart-box").css("display") == "block"){ 
                    $(".cart-box").trigger( "click" ); 
                }
            })
            e.preventDefault();
        });

//Show Items in Cart
    $( ".cart-box").click(function(e) { 
        e.preventDefault(); 
        $(".shopping-cart-box").fadeIn(); 
        $("#shopping-cart-results").html('<img src="images/ajax-loader.gif">'); 
        $("#shopping-cart-results" ).load( "cart_process.php", {"load_cart":"1"}); 
    });

//Close Cart
    $( ".close-shopping-cart-box").click(function(e){ 
        e.preventDefault(); 
        $(".shopping-cart-box").fadeOut(); 
    });


//Remove items from cart
    $("#shopping-cart-results").on('click', 'a.remove-item', function(e) {
        e.preventDefault(); 
        var pcode = $(this).attr("data-code"); 
        $(this).parent().fadeOut(); 
        $.getJSON( "cart_process.php", {"remove_code":pcode} , function(data){ 
            $("#cart-info").html(data.items); 
            $(".cart-box").trigger( "click" );
        });
    });

});
</script>

<?php
$que = "SELECT * FROM category";
$run = mysql_query($que);
$j = 0;
while($row = mysql_fetch_array($run))
{
    $cat_idd[$j] = $row['cat_id'];
    $cat_namee[$j] = $row['cat_name'];
$j++;
}

for($i = 0;  $i < count($cat_idd);  $i++)
    {
        $que2 = "SELECT * FROM item WHERE cat_id = '$cat_idd[$i]' ";
        $result = mysql_query($que2);
        $run = mysql_num_rows($result);

        echo"<table>";
        echo"<th id = 'hidden'></th>";
        echo"<tr>";
        echo"<td id = 'side' width = '110'>";
        echo "&nbsp;&nbsp;"."<a href='index.php?id=$cat_idd[$i]' style = 'text-decoration: none;' >".$cat_namee[$i]." (".$run.")</a><br><br>";
        echo "</td>";
        echo "</tr>";
        echo "</table>";
    }


require('config.php');
if(isset($_GET['id']))
{
    $cat_id = $_GET['id'];
    $que = "SELECT * FROM item WHERE cat_id = '$cat_id'";
    $run = mysql_query($que);
?>
<form class="form-item">

<a href="#" class="cart-box" id="cart-info" title="View Cart">
<?php 
if(isset($_SESSION["products"])){   
    echo count($_SESSION["products"]); 
}else{
    echo 0; 
}
?>
</a>

<div class="shopping-cart-box">
<a href="#" class="close-shopping-cart-box" >Close</a>
<h3>Your Shopping Cart</h3>
    <div id="shopping-cart-results">
    </div>
</div>

<?php

    while($row = mysql_fetch_array($run))
    {
        $i_id = $row['item_id'];
        $i_name = $row['item_name'];
        $i_quantity = $row['item_quantity'];
        $i_size = $row['item_size'];
        $i_color = $row['item_color'];
        ?>


<?php
$query3 = "SELECT product_name, product_price, product_desc, product_code, product_image, product_discount FROM products_list WHERE item_id = '$i_id' ";
$run3 = mysql_query($query3);


while($row3 = mysql_fetch_array($run3)) {
    ?>

    <ul class="products-wrp">
<li>
<form class="form-item">
<h4><?php echo $row3['product_name']; ?></h4>
<div><img src="images/<?php echo $row3['product_image']; ?>"height = "150" width = "180"></div>
<?php echo "Availabe Quantity: " . $i_quantity . "<br>"; ?>
<?php 
if($row3['product_discount'] == 0)
{
echo "Rs. " . $row3['product_price']; 
}
else
{
echo "NOW ". $row3['product_discount'] . "% OFF!";
echo '<div>Rs. <span style = "text-decoration: line-through;">'.$row3['product_price'].'</span></div>';
$discount = ((($row3['product_discount'])/100) * $row3['product_price']);
$f_price = ($row3['product_price'] - $discount);
echo "Rs. ". $f_price . ".00" ;
}
?>

<div class="item-box">
    <div>
    Color :

    <?php 
$arr = $row["item_color"];  
    $exp = explode("," , $arr);
    echo "<select name='product_color'>";
foreach($exp as $key=>$val) {
    echo "<option value='" . $val . "'>" . $val . "</option>";
}
echo "</select>";
?>
<!--    <select name="product_color">
    <option value="Red">Red</option>
    <option value="Blue">Blue</option>
    <option value="Orange">Orange</option>
    </select>
-->
    </div>

    <div>
    Qty :
    <input type = "number" name = "product_qty" min = "1" max = "<?php echo $i_quantity; ?>" 
    value = "1" title = "Please Enter the Numbers Below Available Quantity Only."> 
<!--
    <select name="product_qty">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    </select>
    </div>
--> 
    <div>
    Size :  

<?php 
$arr = $row["item_size"];  
    $exp = explode("," , $arr);
    echo "<select name='product_size'>";
foreach($exp as $key=>$val) {
    echo "<option value='" . $val . "'>" . $val . "</option>";
}
echo "</select>";
?>  
    <input name="product_code" type="hidden" value="<?php echo $row3['product_code']; ?>">
    <button type="submit">Add to Cart</button>
</div>
</form>
</li>
</ul>
</div>

<?php  }  } }?>
</body>
</html>

Now the very first thing as you click on "Add to Cart" happens is the ajax request to cart_process.php with a json value expected to be returned.

cart_process.php

<?php
session_start(); 
$db_username        = 'root'; 
$db_password        = '';
$db_name            = 'yourdbnamehere'; 
$db_host            = 'localhost';

$currency           = 'Rs. ';
$shipping_cost      = 500; 
$taxes              = array( 
                            'VAT' => 12, 
                            'Service Tax' => 5,
                            'Other Tax' => 10
                            );

$mysqli_conn = new mysqli($db_host, $db_username, $db_password,$db_name); 
if ($mysqli_conn->connect_error) {
    die('Error : ('. $mysqli_conn->connect_errno .') '. $mysqli_conn->connect_error);

// add products to session 
    if(isset($_POST["product_code"]))
    {
        foreach($_POST as $key => $value){
            $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
        }

        $statement = $mysqli_conn->prepare("SELECT product_name, product_price, product_discount FROM products_list WHERE product_code=? LIMIT 1");
        $statement->bind_param('s', $new_product['product_code']);
        $statement->execute();
        $statement->bind_result($product_name, $product_price, $product_discount);


        while($statement->fetch()){ 
            $new_product["product_name"] = $product_name; 
            $new_product["product_price"] = $product_price; 
            $new_product["product_discount"] = $product_discount;  

            if($product_discount == 0)
            {
                $product_price = $product_price;
            }
            else
            {
                $discount = (($product_discount/100) * $product_price);
                $product_price = $product_price - $discount;
            }

            if(isset($_SESSION["products"])){  
                if(isset($_SESSION["products"][$new_product['product_code']])) 
                {
                    unset($_SESSION["products"][$new_product['product_code']]);
            }
            $_SESSION["products"][$new_product['product_code']] = $new_product;     
        }

        $total_items = count($_SESSION["products"]); 
        die(json_encode(array('items'=>$total_items)));  

    }

    // list products in cart 
    if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
    {

        if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){ 
            $cart_box = '<ul class="cart-products-loaded">';
            $total = 0;
            foreach($_SESSION["products"] as $product){ 

                $product_name = $product["product_name"]; 
                $product_price = $product["product_price"];
                $product_code = $product["product_code"];
                $product_qty = $product["product_qty"];
                $product_color = $product["product_color"];
                $product_size = $product["product_size"];
                $product_discount = $product["product_discount"];

            if($product_discount == 0)
            {
                $product_price = $product_price;
            }
            else
            {
                $discount = (($product_discount/100) * $product_price);
                $product_price = $product_price - $discount;
            }

                $cart_box .=  "<li> $product_name (Qty : $product_qty | $product_color  | $product_size ) &mdash; $currency ".sprintf("%01.2f", ($product_price * $product_qty)). " <a href=\"#\" class=\"remove-item\" data-code=\"$product_code\">&times;</a></li>";
                $subtotal = ($product_price * $product_qty);
                $total = ($total + $subtotal);
            }
            $cart_box .= "</ul>";
            $cart_box .= '<div class="cart-products-total">Total : '.$currency.sprintf("%01.2f",$total).' <u><a href="view_cart.php" title="Review Cart and Check-Out">Check-out</a></u></div>';
            die($cart_box); 
        }else{
            die("Your Cart is empty"); 
        }
    }
    // remove item from shopping cart
    if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
    {
        $product_code   = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); 

        if(isset($_SESSION["products"][$product_code]))
        {
            unset($_SESSION["products"][$product_code]);
        }

        $total_items = count($_SESSION["products"]);
        die(json_encode(array('items'=>$total_items)));
    }

Now comes the part when you click on "Check-out" in your add-to-cart box. It takes you to another page (the last one in our case) where you can see all the products that you have bought.

view_cart.php

<?php
session_start();
include("config.inc.php"); //one written above in cart_process.php
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Review Your Cart Before Buying</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<body>
<?php 
if(isset($_COOKIE['user']))
{  
$last = $_COOKIE['user']; 
echo '<a href = "signout.php" id = "btn" name ="signout">SignOut</a>';
echo "Logged in: ". $last . "<br><br>"; 


echo '<h3 style="text-align:center">Review Your Cart Before Buying</h3>';

if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){
    $total          = 0;
    $list_tax       = '';
    $cart_box       = '<ul class="view-cart">';

    foreach($_SESSION["products"] as $product){ 
        $product_name = $product["product_name"];
        $product_qty = $product["product_qty"];
        $product_price = $product["product_price"];
        $product_code = $product["product_code"];
        $product_color = $product["product_color"];
        $product_size = $product["product_size"];
        $product_discount = $product["product_discount"];

        if($product_discount == 0)
        {
            $product_price = $product_price;
        }
        else
        {
            $discount = (($product_discount/100) * $product_price);
            $product_price = $product_price - $discount;
        }

        $item_price     = sprintf("%01.2f",($product_price * $product_qty));  // price x qty = total item price

        $cart_box       .=  "<li> $product_code &ndash;  $product_name (Qty : $product_qty | $product_color | $product_size) <span> $currency$item_price </span></li>";

        $subtotal       = ($product_price * $product_qty); 
        $total          = ($total + $subtotal); 
    }

    $grand_total = $total + $shipping_cost; 

    foreach($taxes as $key => $value){ 
            $tax_amount     = round($total * ($value / 100));
            $tax_item[$key] = $tax_amount;
            $grand_total    = $grand_total + $tax_amount; 
    }

    foreach($tax_item as $key => $value){ 
        $list_tax .= $key. ' '. $currency. sprintf("%01.2f", $value).'<br />';
    }

    $shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';

    $cart_box .= "<li class=\"view-cart-total\">$shipping_cost  $list_tax <hr>Payable Amount : $currency ".sprintf("%01.2f", $grand_total)."</li>";
    $cart_box .= "</ul>";

    echo $cart_box;
    echo '<a href = "confirmpurchase.php?conf_pur=check" style = "text-decoration: none; float: right;">Confirm Purchase</a>';
}else{
    echo "Your Cart is empty";
}
}
else
    if(!isset($_COOKIE['user']))
     {
         echo "You must be logged in to purchase!<br>";
         echo '<a href = "login.php" id = "btn" name ="login">Login</a>';

    } 

?>

</body>
</html>

I have run and checked all the processing before posting this here, So it should help you understand the exact behavior and the way to move along.

Cheers.


Need Your Help

jQuery UI: How to set toggle('blind') animation speed? (As in “pixels per second”)

jquery jquery-ui animation toggle

Is it possible to somehow specify the speed of toggle('blind') animation?

Error while trying to use gwt-cal and gwt-dnd

gwt

I have a simple GWT project and I was trying to use the gwt-cal widget but I am getting errors when I try to load a page where I use the widget.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.