0

How do I stop a page from scrolling to the top when button Add to cart is clicked? since i have a lot of products showing up from database to my page, this refreshing the "index.php" to the top is make me frustrated. Btw i'm following this tutorial http://www.onlinetuting.com/e-commerce-website-in-php-mysqli-video-tutorials/

PS: i'm a beginner so just help me with an example (the line where to put the code is important for me).

//index.php (short code only)

<!doctype html>
<?php
include ("functions/functions.php");
?>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="styles/style.css" type="text/css" media="all" />
<script src="js/jquery-3.0.0.min.js"></script>
</head>

<body>
<div class="container">
    <div class="header"></div>

    <div class="navigation">
        <div> <?php getCats(); ?> <?php getBrands(); ?> </div>
        <div> </div>
        <div id="shopping_cart"> <a href="cart.php">Go to Cart</a> <?php total_items(); ?> <?php total_price(); ?> </div>
    </div>

    <div id="content">
        <?php cart(); ?>
        <div id="products"> <?php getPro(); ?> <?php getCatPro(); ?> <?php getBrandPro(); ?> </div>
    </div>

    <div id="footer"></div>
</div> <!--END OF "container" -->
</body>

</html>

//function.php

<?php
$con = mysqli_connect("localhost","root","","learning-php");
if (mysqli_connect_errno())
  {
   echo "The connection was not established: " . mysqli_connect_error();
  }

//Creating the shopping cart
    function cart(){
    if(isset($_GET['add_cart'])){
        global $con;
        $ip = getIp();
        $pro_id = $_GET['add_cart'];
        $check_pro = "select * from cart where ip_add='$ip' AND p_id='$pro_id'";
        $run_check = mysqli_query($con, $check_pro);
        if(mysqli_num_rows($run_check)>0){  
        }
        else {
        $insert_pro = "insert into cart (p_id,ip_add) values ('$pro_id','$ip')";
        $run_pro = mysqli_query($con, $insert_pro);
        echo "<script>window.open('index.php','_self')</script>";   
        }
    }   
    }


    //Getting the total added items
    function total_items(){
        if(isset($_GET['add_cart'])){
            global $con;
            $ip = getIp();
            $get_items = "select * from cart where ip_add='$ip'";
            $run_items = mysqli_query($con, $get_items);
            $count_items = mysqli_num_rows($run_items);
            }
            else {
            global $con;
            $ip = getIp();
            $get_items = "select * from cart where ip_add='$ip'";
            $run_items = mysqli_query($con, $get_items);
            $count_items = mysqli_num_rows($run_items);
            }
        echo $count_items;
        }


    //Getting the total price of the items in the cart
    function total_price(){     
        $total = 0;
        global $con;
        $ip = getIp();  
        $sel_price = "select * from cart where ip_add='$ip'";   
        $run_price = mysqli_query($con, $sel_price);    
        while($p_price=mysqli_fetch_array($run_price)){
            $pro_id = $p_price ['p_id'];
            $pro_price = "select * from products where product_id='$pro_id'";
            $run_pro_price = mysqli_query($con,$pro_price);
            while($pp_price = mysqli_fetch_array($run_pro_price)){  
            $product_price = array($pp_price['product_price']);
            $values = array_sum($product_price);
            $total +=$values;
            }           
        }       
        echo "$ " . $total;     
    }


    //Getting the categories
    function getCats(){
        global $con;
        $get_cats = "select * from categories";
        $run_cats = mysqli_query($con, $get_cats);
        while ($row_cats=mysqli_fetch_array($run_cats)){
            $cat_id = $row_cats['cat_id'];
            $cat_title = $row_cats['cat_title'];
        echo "<li><a href='index.php?cat=$cat_id'>$cat_title</a></li>";
        }
    }


    //Getting the brands
    function getBrands(){
        global $con;
        $get_brands = "select * from brands";
        $run_brands = mysqli_query($con, $get_brands);
        while ($row_brands=mysqli_fetch_array($run_brands)){
            $brand_id = $row_brands['brand_id'];
            $brand_title = $row_brands['brand_title'];
        echo "<li><a href='index.php?brand=$brand_id'>$brand_title</a></li>";
        }
    }


    //Showing the products
    function getPro(){
        if(!isset($_GET['cat'])){
            if(!isset($_GET['brand'])){

        global $con;
        $get_pro = "select * from products";
        $run_pro = mysqli_query($con, $get_pro);
        while ($row_pro=mysqli_fetch_array($run_pro)){
            $pro_id = $row_pro['product_id'];
            $pro_cat = $row_pro['product_cat'];
            $pro_brand = $row_pro['product_brand'];
            $pro_title = $row_pro['product_title'];
            $pro_price = $row_pro['product_price'];
            $pro_image = $row_pro['product_image'];

            echo "
                    <div id='products'>
                        <h3>$pro_title</h3>
                        <img src='admin_area/product_images/$pro_image' width='135' height='100'/>
                        <div class='details'>
                          <p><div id='prc'>Price:</br><b>$. $pro_price </b></div></p>
                          <p><div id='a2c'><a href='?add_cart=$pro_id'><button style='float:left;'>Add to Cart</button></a></div></p>                     
                          <p><div id='fDtl'><a href='full_details.php?pro_id=$pro_id' style='float:left;'>Full Details</a></div></p>
                        </div>
                    </div>
            ";
        }
        }
    }
    }

    //Showing the products by categories
    function getCatPro(){bla,bla,bla}

    //Showing the products by brands
    function getBrandPro(){bla,bla,bla}

?>

//what i mean is this line (function.php) div#a2c

//effected to this line (index.php) div#products

See What i mean

Fanya
  • 1
  • 1
  • 6
  • Remove the `href`? – Script47 Aug 16 '16 at 20:57
  • it doesn't scroll to the top, the whole page reloads, and new pages start at the top. so a, dont relaod the page (ajax). b, add anchors to know where to return to –  Aug 16 '16 at 20:58
  • @Script47 and that suggestion alone fixes OP's current issue and will not cause subsequent issues? – MonkeyZeus Aug 16 '16 at 20:58
  • upz, yup that's correct. my bad. so how can i make it stay in current mouse clicked position, just like refreshing the browser. – Fanya Aug 16 '16 at 21:01
  • @chris85 I thought it had been messed with as I saw [this](https://gyazo.com/d02a1b46eaaad2e8ce1c69fbc78f54f3). – Script47 Aug 16 '16 at 21:01
  • Have the link (or a button) run a JS function to add the item and don't have it use the default action. AJAX probably then https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault – chris85 Aug 16 '16 at 21:02
  • I've updated the tags. Although PHP is generating this the issue is client side. – chris85 Aug 16 '16 at 21:04
  • browser always refreshing and back to the top every time i clicked this button: Sorry, i'm a beginner, so can anyone give more details to fix it? thanks b4. – Fanya Aug 16 '16 at 21:21
  • Still waiting your response guys, with example of course :) – Fanya Aug 16 '16 at 21:28

2 Answers2

0

Override default form submit by calling preventDefault and call the action as a ajax call. Make sure that the script is loaded like put it in head section

refer this example:

var element = document.querySelector("form");
element.addEventListener("submit", function(event) {
  event.preventDefault();
  // actual logic, e.g. validate the form
  alert("Form submission cancelled.");
});
<form>
  <button type="submit">Submit</button>
</form>
Amit Mahajan
  • 895
  • 6
  • 34
  • It's not working, still refreshing and back to the top – Fanya Aug 16 '16 at 22:13
  • Yes if page submit happens it will reload and reach top, you can define some ID and add that to the URL after # like url#id, so after submit it will display your ID. But best option is to not to do page submit unless required as this saves network roundtrip. – Amit Mahajan Aug 16 '16 at 22:15
  • hi amitmah, can you give me an example where and how to put some code that can be solve my problem? this is how the page look like https://drive.google.com/file/d/1CWCo-CLNSIhRGig3nM1vhryaeE5gWfEvyA/view – Fanya Aug 18 '16 at 22:57
  • So you do a page submit to add page correct as per a href link. Refer this example script: document.getElementById("myCheckbox").addEventListener("click", function(event){ event.preventDefault() }); I suggest following steps: 1. Prevent form submit till you want it using above script in head section 2. put the #products in the a href like – Amit Mahajan Aug 18 '16 at 23:33
0

Here is a complete example from http://www.tutorialspoint.com/jquery/events-preventdefault.htm:

<html>

   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("a").click(function(event){
               event.preventDefault();
               alert( "Default behavior is disabled!" );
            });
         });
      </script>
   </head>

   <body>
      <span>Click the following link and it won't work:</span>
      <a href = "http://www.google.com">GOOGLE Inc.</a>
   </body>

</html>
Amit Mahajan
  • 895
  • 6
  • 34