Thanoo February 2016

jquery cookies / javascript cookies

I'm have planned to design a jewelry website with add to cart option. but i still don't know how to keep the selected items on the cart even after refreshing the page through jquery. so if anyone knew please provide an step by step example or tutorial.

Answers


Kyle E4K February 2016

You can use a simple JQuery get method which links to a PHP file which adds the product to the Site cookies; when you want to view the cart, explode the cookie.

An example:

$(document).ready(function(){
    $("#product").click(function(){
        // However you want to get the item ID
        var itemID = document.getElementById("productID").value;
        $.get("/inc/addtocart.php", { item: itemID }, function(data){
             document.getElementById("result-sec").innerHTML=data;
        });
   });           
 });

Your PHP file will look like this:

if(isset($_GET['item'])){
    $_COOKIE['cart_ids'] = $_COOKIE['cart_ids'] . '::' . $_GET['item'];
}

To view your cart items, simply:

$all_items = explode("::", $_COOKIE['cart_ids']);
foreach($all_items as $item):
    echo $item . "<br />";
endforeach;

Post Status

Asked in February 2016
Viewed 1,941 times
Voted 13
Answered 1 times

Search




Leave an answer