Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- PHP processing - trolley1.php
- <?php
- session_start();
- $product_ids = array();
- //check if Add to Cart button has been submitted
- if(filter_input(INPUT_POST, 'submit')){
- if(isset($_SESSION['cart'])){
- //keep track of how many products are in the cart
- $count = count($_SESSION['cart']);
- //create array for matching array keys to products id's
- $product_ids = array_column($_SESSION['cart'], 'id');
- if (!in_array(filter_input(INPUT_GET, 'id'), $product_ids)){
- $_SESSION['cart'][$count] = array(
- 'id' => filter_input(INPUT_GET, 'id'),
- 'name' => filter_input(INPUT_POST, 'name'),
- 'price' => filter_input(INPUT_POST, 'price'),
- 'quantity' => filter_input(INPUT_POST, 'quantity')
- );
- }
- else { //product already exists, increase quantity
- //match array key to id of the product being added to the cart
- for ($i = 0; $i < count($product_ids); $i++){
- if ($product_ids[$i] == filter_input(INPUT_GET, 'id')){
- //add item quantity to the existing product in the array
- $_SESSION['cart'][$i]['quantity'] += filter_input(INPUT_POST, 'quantity');
- }
- }
- }
- }
- else { //if shopping cart doesn't exist, create first product with array key 0
- //create array using submitted form data, start from key 0 and fill it with values
- $_SESSION['cart'][0] = array(
- 'id' => filter_input(INPUT_GET, 'id'),
- 'name' => filter_input(INPUT_POST, 'name'),
- 'price' => filter_input(INPUT_POST, 'price'),
- 'quantity' => filter_input(INPUT_POST, 'quantity')
- );
- }
- }
- cart.php
- <script>
- $(document).ready(function(){
- $('form[id=ajax]').submit(function(event){
- event.preventDefault();
- var formData = {
- submit: $('input[name=submit]').val(),
- id: $('input[name=id]').val(),
- name: $('input[name=name]').val(),
- price: $('input[name=price]').val(),
- quantity: $('input[name=quantity]').val()
- };
- $.ajax({
- type: 'POST',
- url: 'trolley1.php',
- data: formData,
- dataType: 'json',
- });
- });
- });
- </script>
- <?php
- echo "
- <div class='col-sm-3 mt-5'>
- <form id='ajax' method='post' action='trolley1.php?action=add&id=$id'>
- <div class='products'>
- <input id='form_id' type='hidden' name='id' value='$id' />
- <input id='form_name' type='hidden' name='name' value='$product' />
- <input id='form_price' type='hidden' name='price' value='$price' />
- <input id='form_quantity' type='text' name='quantity' class='form-control' value='1' />
- <input id='submit' type='submit' name='submit' style='margin-top:5px;' class='btn btn-info'
- value='Add'/>
- <div id='get_content'></div>
- </div>
- </form>
- </div>
Add Comment
Please, Sign In to add comment