Dj Techblog

A blog on web development

Add to shopping cart via ajax call in php

Last modified on June 2, 2022
Register user with admin approval in php

Shopping cart with ajax and jquery makes an shopping website classic and user friendly and it is not very difficult to add to your already running php shopping website. It is an important feature of every ecommerce webiste. It can be easily added into website running php. But with ajax/jquery we can extra features to it to make a more stylish website. It allows the user to add as many products into his/her shopping cart and later check out with all the items at a time. The user can view, delete or add the items to his cart any time. This makes shopping easy and user friendly.

In this project we will build a demo shopping cart using php ajax and javascript library jquery. This kind of shopping cart can be added to any kind of online shopping websites.

I have also written a blog to build a simple shopping cart with php only.

Add a shopping cart to ecommerce website in php

Let's see how to add to shopping cart via ajax call in php.

Recommended read,

Admin panel with Category Subcategory setup for ecommerce website in php

Admin panel to add update delete products for ecommerce webiste in php

We will follow these basic steps to complete this project:

  1. Create a cart table in the database.
  2. Design the index.php page in php
  3. Design product-details page with add to cart button for every product
  4. Add to the shopping cart making an ajax request to server.
  5. View cart in php
  6. Delete the item from the shopping cart in php

Recommended read,

Regsiter user with admin approval in php

Create a cart table in the database.

The cart table will have four fields pid,name,price,image. pid is the primary key.

    CREATE TABLE cart (pid INT NOT NULL, name TEXT NOT NULL, price INT NOT NULL, image TEXT NOT NULL, email TEXT NOT NULL );

Design index.php page

The index page displays all the products from the database. Clicking on the product takes the user to product details page where user can add the product to the cart.

<?php session_start();
            
?>
<?php           
                $db = mysqli_connect('localhost', 'user-name', 'password', 'database-name');
                $query = "SELECT * FROM category";
                $result = mysqli_query($db, $query);
                if ($result == FALSE) {
                    die(mysqli_error());
                    exit();
                }
                $query1 = "SELECT * FROM products";
                $result1 = mysqli_query($db, $query1);
                if ($result1 == FALSE) {
                    die(mysqli_error());
                    exit();
                }
?>

<!DOCTYPE html>
<html lang="en-us">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Ecommerce website</title>
        <!-- CSS only -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
        
        <style>
            .closebtn:hover {
              color: black;
            }
                    
             .width{
                width: 600px;
            }
            @media(max-width: 600px)
            {
                .width{
                width: 350px;
            }
            } 
            .width{
                width: 600px;
            }
            @media(max-width: 600px)
            {
                .width{
                width: 350px;
            }
            }
            .wid{
                width: 400px;
            }
            .error{
                color: red;
                font-size: large;
                display: none;
            
            }
            .success{
                color: green;
                font-size: large;
                display: none;
            }
            
            img{
                margin: auto;
                border-radius: 3px;
                border: 1px solid grey;
                height: 190px;
                width: 180px;
            }
        </style>
        
          </head>
    <body>
        <nav class="navbar navbar-expand-lg navbar-light bg-primary">
              <div class="container">
                <a class="navbar-brand text-light font-weight-bold" href="index.php">Ecommerce</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
                  <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNavDropdown">
                  <ul class="navbar-nav">
                    <li class="nav-item ">
                      <a class="nav-link text-light" href="home.php" >
                        <?php if(!isset($_SESSION['email']))
                                    echo "Login";
                              else
                                    echo $_SESSION['fname']
                        ?>
                      </a>
                      
                    </li>
                    
                    <li class="nav-item">
                      <a class="nav-link text-light" href="register.php" >
                       <?php if(!isset($_SESSION['email']))
                                    echo "Register";
                        ?>
                      </a>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link text-light" href="logout.php" >
                       <?php if(isset($_SESSION['email']))
                                    echo "Logout";
                        ?>
                      </a>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link text-light" href="home.php" >
                       <?php if(isset($_SESSION['email']))
                                    echo "View cart";
                        ?>
                      </a>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link text-light" href="home.php" >
                       <?php if(isset($_SESSION['email']))
                                    echo "Check out";
                        ?>
                      </a>
                    </li>
                  </ul>
                  <form class="d-flex mx-sm-5">
                    <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
                    <button class="btn btn-outline-light" type="submit">Search</button>
                  </form>
                </div>
              </div>
        </nav>
        
          <div id="carouselExampleControls" class="carousel slide pt-5 pb-5" data-bs-ride="carousel">
              <div class="carousel-inner">
                <div class="carousel-item active">
                    <?php $row = mysqli_fetch_array($result, MYSQLI_ASSOC); ?>
                  <h1 class="text-center pt-5"><?php echo $row['name']; ?></h1>
                </div>
                <div class="carousel-item">
                     <?php $row = mysqli_fetch_array($result, MYSQLI_ASSOC); ?>
                  <h1 class="text-center pt-5"><?php echo $row['name']; ?></h1>
                </div>
                <div class="carousel-item">
                     <?php $row = mysqli_fetch_array($result, MYSQLI_ASSOC); ?>
                  <h1 class="text-center pt-5"><?php echo $row['name']; ?></h1>
                </div>
                <div class="carousel-item">
                     <?php $row = mysqli_fetch_array($result, MYSQLI_ASSOC); ?>
                  <h1 class="text-center pt-5"><?php echo $row['name']; ?></h1>
                </div>
                <div class="carousel-item">
                     <?php $row = mysqli_fetch_array($result, MYSQLI_ASSOC); ?>
                  <h1 class="text-center pt-5"><?php echo $row['name']; ?></h1>
                </div>
              </div>
              <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                <span class="visually-hidden">Previous</span>
              </button>
              <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                <span class="visually-hidden">Next</span>
              </button>
          </div>
          
          <div class="container pt-5 pb-5">
            <?php 
                $result = mysqli_query($db, $query); 
            while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { ?>
            <div class="row pt-5">
                <?php while($row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC)) { ?>
                <div class="col-sm-3">
                    <div class="card" style="width: 18rem;">
                          <a href="<?php echo 'product-details.php' . '?pid=' . $row1['pid'] ; ?>" class="text-decoration-none" >
                           <div class="card-body">
                                <img src="<?php echo $row1['image1']; ?>" class="card-img-top" alt="...">
                                <h5 class="pt-3 card-title"><?php echo $row1['name']; ?></h5>
                                <p class="card-text">Product id. <?php echo $row1['pid']; ?></p>
                                <p class="card-text pb-3">Price: Rs. <?php echo $row1['price']; ?></p>
                           </div>
                          </a>
                    </div>
                </div>
                <?php }?>
            </div>
            <?php }?>
           </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <!-- JavaScript Bundle with Popper -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
        
    </body>
</html>
                    

Design product-details.php page

It contains the product name, image, price and an Add to cart button. Clicking on the add to cart button calls a javascript function.

The javascript function receive all the product values from the form and makes an ajax call to the php server. The server first check for the login status of the user. If the user is not logged in, ask user to login first. The logged in user is able to add the prodcut to the cart. However, if the product is already in the cart, display the message to the user.

<?php session_start();
            if(isset($_SESSION['email']))
            {
                if($_SESSION['email'] == "mm@mm.mm"){
                  header("location:admin-panel.php");
                  die();
                }
            }
?>
<?php           
                include('db-connect.php');
                $pid = $_GET['pid'];
                $query = "SELECT * FROM products1 WHERE id='$pid'";
                $result = mysqli_query($db, $query);
                if ($result == FALSE) {
                    die(mysqli_error());
                    exit();
                }
                $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
                
                $query = "SELECT * FROM product_images WHERE pid='$pid'";
                $result1 = mysqli_query($db, $query);
                if ($result1 == FALSE) {
                    die(mysqli_error());
                    exit();
                }
                $result1 = mysqli_query($db, $query);
                $row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);
                
?>

<!DOCTYPE html>
<html lang="en-us">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Ecommerce website</title>
        <!-- CSS only -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
        
        <style>
            
                 
            .width{
                width: 600px;
            }
            @media(max-width: 600px)
            {
                .width{
                width: 350px;
            }
            } 
            .width{
                width: 600px;
            }
            @media(max-width: 600px)
            {
                .width{
                width: 350px;
            }
            }
            .wid{
                width: 400px;
            }
            .error{
                color: red;
                font-size: large;
                display: none;
                cursor: pointer;
                position: fixed;
              width: 100%;
              height: 5%;
              top: 1;
              left: 0;
              right: 0;
              bottom: 10;
              background-color: #eee;
              z-index: 2;
              opacity: 0.7;
            }
            .success{
                color: green;
                font-size: large;
                display: none;
                cursor: pointer;
                width: 100%;
                  height: 5%;
                  top: 1;
                  left: 0;
                  right: 0;
                  bottom: 10;
                  background-color: #eee;
                  z-index: 2;
                  opacity: 0.7;
            }
            
            .image{
                margin: auto;
                border-radius: 3px;
                border: 3px solid grey;
                height: 490px;
                width: 580px;
            }
        </style>
        
          </head>
      <body>
        <nav class="navbar navbar-expand-lg navbar-light bg-primary">
              <div class="container">
                <a class="navbar-brand" href="index.php">Ecommerce</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
                  <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNavDropdown">
                  <ul class="navbar-nav">
                    <li class="nav-item ">
                      <a class="nav-link" href="home.php" >
                        <?php if(!isset($_SESSION['email']))
                                    echo "Login";
                              else
                                    echo $_SESSION['fname']
                        ?>
                      </a>
                      
                    </li>
                    
                    <li class="nav-item">
                      <a class="nav-link" href="register.php" >
                       <?php if(!isset($_SESSION['email']))
                                    echo "Register";
                        ?>
                      </a>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link" href="logout.php" >
                       <?php if(isset($_SESSION['email']))
                                    echo "Logout";
                        ?>
                      </a>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link" href="home.php" >
                       <?php if(isset($_SESSION['email']))
                                    echo "View cart";
                        ?>
                      </a>
                    </li>
                  </ul>
                  <form class="d-flex mx-sm-5">
                    <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
                    <button class="btn btn-outline-light" type="submit">Search</button>
                  </form>
                </div>
              </div>
        </nav>
          
            <div class="error mx-auto w-25 ps-5 overlay" role="alert" onclick="this.style.display='none';">
                
            </div>
            <div class="success w-25 mx-auto ps-5 alert overlay" role="alert">
               
            </div>
          
          <div class="container pt-5 pb-5">
                <div class="container w-75 mx-auto">
                                <img class="mx-auto d-block image" src="<?php echo $row1['image']; ?>" alt="<?php echo $row['product_name']; ?>">
                                <h5 class="pt-3 text-center"><?php echo $row['product_name']; ?></h5>
                                <p class="text-center">Product id. <?php echo $row['id']; ?></p>
                                <p class="text-center pb-3">Price: Rs. <?php echo $row['price']; ?></p>
                                <form id="the-form" method="post" enctype="multipart/form-data">
                                    <input type="hidden" name ="pname" value="<?php echo $row['product_name']; ?>">
                                    <input type="hidden" name ="pid" value="<?php echo $row['id']; ?>">
                                    <input type="hidden" name ="price" value="<?php echo $row['price']; ?>">
                                    <input type="hidden" name ="image" value="<?php echo $row['image']; ?>">
                                    <input type="hidden" name = "email" value="<?php echo $_SESSION['email']; ?>">
                                    <div class="row w-75 mx-auto">
                                        <div class="col-sm-4">
                                            <button type="button" class="btn btn-outline-primary">Proceed to Buy</button>
                                        </div>
                                        <div class="col-sm-4">
                                            <button type="button" onclick="addtocart()" class="btn btn-outline-primary">Add to cart</button>
                                        </div>
                                        <div class="col-sm-4">
                                            <a href="index.php" class="btn btn-outline-primary">Continue Shopping</a>
                                        </div>
                                    </div>
                                </form>
                </div>
          </div>
        <script src="script151.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <!-- JavaScript Bundle with Popper -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
        
        <script>
            function addtocart(){
                event.preventDefault();
                var form = $('#the-form')[0];
                var data = new FormData(form);
                $.ajax({
                    type: "POST",
                    enctype: 'multipart/form-data',
                    url: "addtocart.php",
                    data: data,
                    processData: false,
                    contentType: false,
                    cache: false,
                    success : function(response)
                    {
                        if(response == 1 ){
                            $('.success').html("Product added to cart.").show();
                            $('.error').hide();
                            
                        }
                        else{
                            if(response == 2){
                                $('.success').html("Product already in the cart").show();
                                $('.error').hide(); 
                            }
                            else{
                                if(response == 4){
                                    $('.error').html("Please, login first").show();
                                    $('.success').hide();
                                }
                            }
                        }
                    },
                    error : function()
                    {
                         $('.error').html("Error").show();
                         $('.success').hide();
                     
                    }
                });
            }
        </script>
        
    </body>
</html>
                    

addtocart.php: Add to the shopping cart making an ajax request to server.

It receives all the product infromation from the front end and add it to the cart table in the database. If the product is already in the cart, display the suitable message to the user.

<?php
include('db-connect.php');
session_start();
 
error_reporting(E_ALL & ~ E_NOTICE);

class Controller
{
    function __construct() 
    {
        $this->processMobileVerification();
    }
    function processMobileVerification()
    {
                        if(!isset($_SESSION['email'])){
                            echo 4;
                        }
                        else
                        {
                            $pid = $_POST['pid'];
                            $name = $_POST['pname'];
                            $price =  $_POST['price'];
                            $image = $_POST['image'];
                            $email = $_POST['email'];
                            $query1 = "SELECT * FROM cart WHERE pid= '$pid' && email='$email' ";
                            $result1 = mysqli_query($db,$query1);
                            $row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);
                            if(!$row1['pid']){
                                $query= "INSERT INTO cart (pid,name,price,image,email) VALUES('$pid','$name','$price','$image','$email')";
                                $result = mysqli_query($db,$query);
                                if(!$result){
                                    die(mysqli_error());
                                    echo 3;
                                    exit();
                                }
                                else
                                    echo 1;
                            }
                            else 
                                echo 2;
                                
                        }           
    }
}
$controller = new Controller();
?>

home.php: View cart/ Delete item from the cart

The home page displays all the items in the cart with all the related details. It also contains the delete option for every item in the cart. The user can delete the items in the cart any time and continue to shopping or proceed to final checkout.

<?php session_start();
        if(!isset($_SESSION['email'])){
            header('location: login.php');
        }
                $email = $_SESSION['email'];
                include('db-connect.php');              
?>
<!DOCTYPE html>
<html lang="en-us">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Home page</title>
        <!-- CSS only -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
        
        <style>
            .image{
                margin: auto;
                border-radius: 3px;
                border: 3px solid grey;
                height: 90px;
                width: 180px;
            }
            .width{
                width: 600px;
            }
            @media(max-width: 600px)
            {
                .width{
                width: 350px;
            }
            }
            .error{
                color: red;
                font-size: large;
            
            }
            
            #message3{
                color: red;
            }   
        </style>
          </head>
    <body class="bg-light">
        <div class="container-fluid pt-5 bg-light">
            <div class="row">
                <div class="col-sm-6">
                    <p class="text-center">Hello <?php echo $_SESSION['fname']; ?></p>
                    <p class="text-center">
                        <img class="rounded" src="<?php echo ("/test123/profile-pic/") . ($_SESSION['email']) . "display-picture.jpg"; ?>" width="150px" height="140px">
                    </p>
                    <form class="pt-2 w-50 mx-auto" method="post" enctype="multipart/form-data">
                    <p class="text-center text-danger"><strong>Upload Profile picture</strong></p>
                    <input type="file" name="fileToUpload" class="form-control" id="fileToUpload">
                    <p></p>
                    <input type="submit" class="form-control btn btn-primary" value="Upload Image" name="submit">
                    <p> 
                    <?php include_once('upload.php'); ?>
                    </p>
                </form>
                </div>
                <div class="col-sm-6">
                    <p class="text-center"><a href="logout.php" class="btn btn-primary">Logout</a></p>
                    <p class="text-center"><a href="show-data-1.php" class="btn btn-primary">Show data</a></p>
                </div>
            </div>
        </div>
        <div class="container-fuid w-50 mx-auto">
                <h2 class="text-center pt-5 pb-5"><strong>Cart</strong></h2>
                <div class="table table-responsive">
                            <table class="table table-striped w-100 table-bordered">
                                <thead class="table-primary">
                                    <tr>
                                      <th class="text-left">Sl No.</th>
                                      <th class="text-left">Name</th>
                                      <th class="text-left">Product id</th>
                                      <th class="text-left">INR Price </th>
                                      <th class="text-center">Picture</th>
                                      <th class="text-center">Delete</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php 
                                $query = "SELECT * FROM cart WHERE email = '$email' ";
                                $result = mysqli_query($db, $query);
                                $i=1; while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { ?>    
                                <tr>
                                  <td><?php echo $i++; ?></td>
                                  <td><?php $items = $items ." " . $row['name']; echo($row['name']); ?></td>
                                  <td><?php echo($row['pid']); ?></td>
                                  <td>Rs. <?php $price += $row['price']; echo($row['price']); ?> ₹ </td>
                                  <td><img class="image mx-auto d-block" src="<?php echo($row['image']); ?>"></td>
                                  <td>
                                      <form action="home.php" method="post">
                                           <input type="hidden" name="pid" value="<?php echo($row['pid']); ?>">
                                           <button class="btn btn-primary mx-auto d-block">Delete</button>
                                      </form>
                                      
                                  </td>
                                </tr>
                                <?php } ?>
                                <tr>
                                    <td><strong>Total items</strong>:</td>
                                    <td class="text-center"><strong><?php echo --$i; ?></strong></td>
                                    <td><strong>Total price </strong>:</td>
                                    <form action="stripe/pay.php" method="post">
                                         <input type="hidden" value="<?php echo $price; ?>" name="price" >
                                         <input type="hidden" value="<?php echo $items; ?>" name="items" >
                                         <td><strong>Rs. <?php echo $price; ?> ₹ </strong></td>
                                         <td class="text-center"><a href="index.php" class="btn btn-outline-success">Continue Shopping</a></td>
                                         <td class="text-center"><button type="submit" class="btn btn-success">Checkout</td>
                                    </form>
                                </tr>
                              </tbody>
                            </table> 
                </div> 
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <!-- JavaScript Bundle with Popper -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
    </body>
</html>
<?php           // Delete the items from cart
                $pid = $_POST['pid'];
                $query = "DELETE FROM cart WHERE pid='$pid'";
                $result = mysqli_query($db, $query);
                if(!$result){
                    die(mysqli_error());
                    exit();
                }
?>

Published on July 16, 2021


Ad section

Intro

Debabratta Jena

I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

Reach to me in the contact us form below

Follow me on

Contact us

Subscribe

Tags

Php HTML5 Javascript CSS Ajax Angular JS Google My bisiness Listing Google tag Manager Google Universal Analytics Search Engine Optimization On page SEO Off page SEO Google Marketing platform Digital Marketing Google Ads Mysql Apache Server

Ad section
×

Subscribe to get email notification about our new post

Name

Email

We neither sell nor share your personal information with any third party. Your identity is safe with us.