I now have a simple "shopping cart" script that I have converted to an "add to shortlist" script to better suit my website.
Everything wokrs great however after you click the add to shortlist link it goes to the shortlist page.
Here is the code for "add to shortlist"

<a href = "http://www.xxxxxxxx.com/shortlist.php?action=add&id=' . $id . '" <b>Add to Shortlist<b> </a>

Is it possible to stay on the page after this is clicked rather than going straight to the shortlist page?
Here is the code for my shortlist page.

<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<style type="text/css">
<!--
body {
    background-color: #E8E1C3;
}
-->
</style>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script> 
$(document).ready(function(){
  $(".flip").click(function(){
   $(this).next('.panel').slideToggle('slow');
  });
});
</script>
<title>Shortlist</title>


<?php
    include("header_1.php");
    include ("Connections.php");
    include("header.php");
    include("heading.php");
?>


</head>
<body>
<div id='content'><div id='output'>

<?php

    $product_id = (empty($_GET['id']) ? 0 : $_GET['id']);    //the product id from the URL 
    $action     = (empty($_GET['action']) ? 0 : $_GET['action']); //the action from the URL 

    //if there is an product_id and that product_id doesn't exist display an error message
    if($product_id && !productExists($product_id)) {
        die("Error. Product Doesn't Exist");
    }

    switch($action) {   //decide what to do 

        case "add":
            $_SESSION['cart'][$product_id] = (array_key_exists($product_id, $_SESSION['cart'])) ? $_SESSION['cart'][$product_id] +1 : 1; //add one to the quantity of the product with id $product_id 
        break;

        case "remove":
            $_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id 
            if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items. 
        break;

        case "empty":
            unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart. 
        break;

    }

?>


<?php    

    if(isset($_SESSION['cart'])) {  //if the cart isn't empty
        //show the cart

        echo "<table border=\"0\" padding=\"0\" width=\"100%\">";    //format the cart using a HTML table

            //iterate through the cart, the $product_id is the key and $quantity is the value
            foreach($_SESSION['cart'] as $product_id => $quantity) {    

                //get the name, description and price from the database - this will depend on your database implementation.
                //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
                $sql = sprintf("SELECT  name,  colour, sex FROM employees WHERE id = %d;",
                                $product_id); 

                $result = mysql_query($sql);

                //Only display the row if there is a product (though there should always be as we have already checked)
                if(mysql_num_rows($result) > 0) {

                    list($name,  $colour, $sex  ) = mysql_fetch_row($result);


                    echo "<tr>";
                    echo "<td align=\"left\" > <span class=\"style40\" >$name  </span class>    <span class=\"style90\" >$colour  $sex  $dob</span class></td>";
                    echo "</tr>";


                        echo"</tr>";
                        echo"<tr>";
                        echo "<td align=\"center\"> <a href=\"$_SERVER[PHP_SELF]?action=remove&id=$product_id\">Remove from shortlist</a></td>";
                        echo "</tr>";




                }

            }



            //show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation
            echo "<tr>";
                echo "<td colspan=\"3\" align=\"right\"><a href=\"$_SERVER[PHP_SELF]?action=empty\" onclick=\"return confirm('Are you sure?');\">CLEAR ALL FROM SHORTLIST</a></td>";
            echo "</tr>";        
        echo "</table>";



    }else{
        //otherwise tell the user they have no items in their cart
        echo "You have no items in your shortlist.";

    }

    //function to check if a product exists
    function productExists($product_id) {
            //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
            $sql = sprintf("SELECT * FROM test WHERE id = %d;",
                            $product_id); 

            return mysql_num_rows(mysql_query($sql)) > 0;
    }
?>

<a href="test.php">Continue Browsing</a>




</div></div>
 <?php include ("footer.php"); ?>
</body>
</html>

You can accomplish this with ajax. Kind of like this:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
<script type="text/javascript">
    jQuery(document).ready(function($){
        $('#button').on('click', function(e){
            e.preventDefault();
            $.ajax({
                url: 'path/to/script.php',
                type: 'POST',
                data: {user_id: $_SESSION['user_id'], liked: true, url_slug: $(location).attr('href')},
                cache: false,
                success: function(data){
                    alert(data);
                }
            });
        });
    });
</script>

Where should I place this code?

you would need to edit the data and create a script.php page or point to where you have do your validaiton and processing.. but to anwser your question, you would place in the header or footer of your page.

For the button you would need to add id of button. <a id="button" href="#">Add to shortlist</a>

This is what you should change for the ajax

url: 'shortlist.php',
data: {action: add, id: <?php echo $id; ?> }

Ok I've done something wrong. Ive added this script to my products page.

<script type="text/javascript">
    jQuery(document).ready(function($){
        $('#button').on('click', function(e){
            e.preventDefault();
            $.ajax({
                url: 'shortlist.php',
                type: 'POST',
                data: {user_id: $_SESSION['cart'], liked: true, url_slug: $(location).attr('href')},
                cache: false,
                success: function(data){
                    alert(data);
                }
            });
        });
    });
</script>

And changed by button to this:

<a href = "http://www.justcuttin.com.au/shortlist.php?onclick=\action=add&id=' . $id . '" <b>Add to Shortlist<b> </a>

Still going to my shortlist page. I'm asuming the javascript goes on the products page where the add to shortlist button is?

No that dosn't work it does stay on the page after clicking but is not adding info to the shortlist.php

<script type="text/javascript">
    jQuery(document).ready(function($){
        $('#button').on('click', function(e){
            e.preventDefault();
            $.ajax({
                url: 'shortlist.php',
                type: 'POST',
                data: {action: add, id: <?php echo $id; ?> },
                cache: false,
                success: function(data){
                    alert(data);
                }
            });
        });
    });
</script>

Button

<a id="button" href="#">Add to shortlist</a>

ok, so what do you think the problem is?

Try checking url: 'path/to/shortlist.php',

Try Changing type: 'POST', to type: 'GET',

Its called troubleshooting.. This is your script or program.. If you have been developing this code, you should know where to troubleshoot the problems.

Aside from the help gabrielcastillo is providing which is excellent, that's only the client side script. This server side script doesnt seem appropriate if you are using to interact with your client side script. The server side script, as written is mean to be used stand-alone.

If you are going to use ajax in your page, then you should be sending specific data to your script (which you are), then process that data and return appropriate data back to your client, then do something clientside with that data. For example, if your script successfully adds something to the cart, then your server script needs to send back something useful, then the client side script should take that information and dynamically update an element on the page to reflect that something was added to the cart.

Does that help and/or make sense to you?

Thanks guys been playing all day with various options to get this to work including suggestions above not making any progress I'm afraid. Javascript is something I havn't got a big handle on.

I'm wondering if there is a code I can add to the shortlist.php that will tell it to go back to the page the id was inserted from? Something like that?

whatever the problem is with the javascript I'm sure it's got something to do with the 'id' as that seems to be where I have been having most problems all along this thing

put this at the top of your shotlist.php file and then press the add button.. you can use firebug and or chrome tools to see the ajax fire off.

//Change the to get if you are using type: 'GET',
if($_POST['action'] == true){
    echo 'Success: you have added this to your shortlist';
}

If all goes well and you are talking with the shortlist script, you should get an alert with the message.

This is the error I'm getting in Chrome

Failed to load resource: net::ERR_CACHE_MISS

Yeah the Javascript dosn't seem to wnat to fire.

Is there a way of just putting some php script on the shortlist.php page that just tells it to go back to the page the GET clause came from? Like the following? (tried this dosn't work)

exit(header('Location: '.parse_url($_SERVER['PHP_SELF'],PHP_URL_PATH)));

Wow.. lol, yeah I guess you can do a redirect.. but you have to set some validation for your GET.

Do you mean on the shortlist.php file or the page the link is on?

Ok I'm going to go with JorgeM and instead of having just a products.php and a shortlist.php file. I'm going to add an "add to shortlist.php" and a "remove from shortlist.php". Will update.

Ok that seemed to do the trick.

products.php page looks like this.

<?php
session_start(); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><style type="text/css">
<!--
body {
    background-color: #E8E1C3;
}
-->
</style>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<link rel="stylesheet" type="text/css" href="sale_barn.css">



<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script> 
$(document).ready(function(){
  $(".flip").click(function(){
   $(this).next('.panel').slideToggle('slow');
  });
});
</script>

<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">


</head>

<body>
<?php 
include '../headers/header_37.php';
include'../headers/sale_barn_header.php';
include'../pagination.php';
include 'layout_head.php';
?>
<div id='content'><div id='search'>
      <img src="/images/Headings/cars.gif" width="400" height="40"><br>  
  <form method="get" action="./search_cars.php">
          <span class="style97">Search By Sire Name: </span>
          <input type='text' name='k' size='50' />
          <input name="submit" type='submit' value='search'>
        </form>
        </div><br></div>
        <div id='content'><div id='output'>
 <?php
// to prevent undefined index notice
$action = isset($_GET['action']) ? $_GET['action'] : "";
$id = isset($_GET['id']) ? $_GET['id'] : "1";
$horsename = isset($_GET['name']) ? $_GET['name'] : "";

if($action=='added'){
    echo "<div class='alert alert-info'>";
        echo "<strong>{$name}</strong> was added to your cart!";
    echo "</div>";
}

if($action=='exists'){
    echo "<div class='alert alert-info'>";
        echo "<strong>{$horsename}</strong> already exists in your cart!";
    echo "</div>";
}

$query = ("SELECT * FROM `test`  WHERE addtype='cars' AND approved='1' AND tm >= NOW() - INTERVAL 365 DAY ORDER BY tm DESC");
$stmt = $con->prepare( $query );
$stmt->execute();

$num = $stmt->rowCount();

if($num>0){

    //start table
    echo "<table class='table table-hover table-responsive table-bordered'>";

        // our table heading
        echo "<tr>";
            echo "<th class='textAlignLeft'>Horse Name</th>";
            echo "<th>Price (USD)</th>";
            echo "<th>Action</th>";
        echo "</tr>";

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            extract($row);

            //creating new table row per record
            echo "<tr>";
                echo "<td>";
                    echo "<div class='id' style='display:none;'>{$id}</div>";
                    echo "<div class='name'>{$name}</div>";
                echo "</td>";
                echo "<td>&#36;{$price}</td>";
                echo "<td>";
                    echo "<a href='add_to_cart.php?id={$id}&name={$name}' class='btn btn-primary'>";
                        echo "<span class='glyphicon glyphicon-shopping-cart'></span> Add to cart";
                    echo "</a>";
                echo "</td>";
            echo "</tr>";
        }

    echo "</table>";
}

// tell the user if there's no products in the database
else{
    echo "No products found.";
}

include 'layout_foot.php';
?>

add_to_cart.php looks like this.

<?php
session_start();

// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$horsename = isset($_GET['name']) ? $_GET['name'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(!isset($_SESSION['cart_items'])){
    $_SESSION['cart_items'] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($id, $_SESSION['cart_items'])){
    // redirect to product list and tell the user it was added to cart
    header('Location: products.php?action=exists&id' . $id . '&name=' . $name);
}

// else, add the item to the array
else{
    $_SESSION['cart_items'][$id]=$name;

    // redirect to product list and tell the user it was added to cart
    header('Location: products.php?action=added&id' . $id . '&name=' . $name);
}
?>

cart.php looks like this:

<?php
session_start();

$page_title="Cart";
include 'layout_head.php';

$action = isset($_GET['action']) ? $_GET['action'] : "";
$horsename = isset($_GET['name']) ? $_GET['name'] : "";

if($action=='removed'){
    echo "<div class='alert alert-info'>";
        echo "<strong>{$name}</strong> was removed from your cart!";
    echo "</div>";
}

else if($action=='quantity_updated'){
    echo "<div class='alert alert-info'>";
        echo "<strong>{$name}</strong> quantity was updated!";
    echo "</div>";
}

if(count($_SESSION['cart_items'])>0){

    // get the product ids
    $ids = "";
    foreach($_SESSION['cart_items'] as $id=>$value){
        $ids = $ids . $id . ",";
    }

    // remove the last comma
    $ids = rtrim($ids, ',');

    //start table
    echo "<table class='table table-hover table-responsive table-bordered'>";

        // our table heading
        echo "<tr>";
            echo "<th class='textAlignLeft'>Product Name</th>";
            echo "<th>Price (USD)</th>";
            echo "<th>Action</th>";
        echo "</tr>";

        $query = "SELECT * FROM test WHERE id IN ({$ids}) ORDER BY name";

        $stmt = $con->prepare( $query );
        $stmt->execute();

        $total_price=0;
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            extract($row);

            echo "<tr>";
                echo "<td>{$name}</td>";
                echo "<td>&#36;{$price}</td>";
                echo "<td>";
                    echo "<a href='remove_from_cart.php?id={$id}&name={$name}' class='btn btn-danger'>";
                        echo "<span class='glyphicon glyphicon-remove'></span> Remove from cart";
                    echo "</a>";
                echo "</td>";
            echo "</tr>";

            $total_price+=$price;
        }

        echo "<tr>";
                echo "<td><b>Total</b></td>";
                echo "<td>&#36;{$total_price}</td>";
                echo "<td>";
                    echo "<a href='#' class='btn btn-success'>";
                        echo "<span class='glyphicon glyphicon-shopping-cart'></span> Checkout";
                    echo "</a>";
                echo "</td>";
            echo "</tr>";

    echo "</table>";
}

else{
    echo "<div class='alert alert-danger'>";
        echo "<strong>No products found</strong> in your cart!";
    echo "</div>";
}

include 'layout_foot.php';
?>

and remove_from_cart.php looks like this:

<?php
session_start();

// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";

// remove the item from the array
unset($_SESSION['cart_items'][$id]);
unset($_SESSION['cart_items'][$name]);

// redirect to product list and tell the user it was added to cart
header('Location: cart.php?action=removed&id=' . $id . '&name=' . $name);
?>

Now my next challenge is to get the pagination part of my script working.
I'm currently getting a warning:

Warning: mysql_num_rows() expects parameter 1 to be resource, string given in /home/xxxxxxx/public_html/pagination.php on line 7

$result= ("SELECT * FROM test WHERE addtype='cars' and approved='1' AND tm >= NOW() - INTERVAL 365 DAY ORDER BY tm DESC");


$num_rows = mysql_num_rows($result); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
    //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;
} 

my connection is:

<?php
$host = "localhost";
$db_name = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";

try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}

//to handle connection error
catch(PDOException $exception){
    echo "Connection error: " . $exception->getMessage();
}
?>

I think I have to modify this to go with the PDO conection settings but PDO is a new thing to me. Any help would be appreiated.
Thanks

Ok I,ve got the add to shortlist function working on my site. It paginates, it gives relevant messages and it looks pretty. Redirecting using

 header('Location: products.php?action=added&id' . $id . '&name=' . $name);

is ok if you have a small list of products, but if your going through lots of products the function can be a tad annoying and confusing. I've tested the scripts with the above redirect taken out and it works despite staying on the add_to_shortlist.php file. So now its time to revisit the javascript idea. Wish me luck!!! gabrielcastillo

Ok taken me a while but the link is now firing using javascript. But now I'm stuck!!

Link looks like this:

"<a id='button' href='add_to_cart.php?id={$id}&name={$name}'>Add to shortlist</a>";

Javascript looks like this:

 <script>
        $( document ).ready(function() { 
        $( "button" ).click(function( event ) {
            event.preventDefault();
            alert( "Added to shortlist!" );

        });

    });


    </script>

!" );

    });

});


</script>

It links to require page but it dosn't stay on the products page after firing and the alert isn't workin either. Phew!!!!

Do you mean on the shortlist.php file or the page the link is on?

not sure what you are referring to?

"<a id='button' href='add_to_cart.php?id={$id}&name={$name}'>Add to shortlist</a>";

Links to the 'add_cart_page'. and the add to cart function works. add to cart is now this.

<?php
session_start();

// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$horsename = isset($_GET['name']) ? $_GET['name'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(!isset($_SESSION['cart_items'])){
    $_SESSION['cart_items'] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($id, $_SESSION['cart_items'])){

}

// else, add the item to the array
else{
    $_SESSION['cart_items'][$id]=$name;


}
?>

As I have removed the redirect headers.

So what I want the javascript to do now is trigger the link to add_to_cart.php (which it does) but instead of going to add_to_cart.php I want it to stay on the page. (preferably staying in the position on the page rather than jumping to the top.

Ok i'm making progress (I think) but it would be nice if someone could tell me if I'm heading in the right direction as I seem to going around in circles.

My link now looks like this.

echo  "<a id='button' href='shopping/add_to_cart.php' onclick='myFunction();'>Add to shortlist</a>";

My javascript is this:

<script>
    function myFunction() {
    event.preventDefault();
    alert("Added to shortlist!");

    }
</script>

What is happening now is if I leave the

event.preventDefault ();

out the link is triggered and the alert appears. If I leave the
code:

event.preventDefault();

in it stays on the page the alert appears but the add_to_cart.php function dosn't trigger.

So this is what I am thinking that I need. I need a peice of code in before

event.preventDefault();

saying do all the work required that is on the add_to_cart.php page but don't actually go there. I'm starting to think that I am totally off track can someone please advise? Thanks

For your information @gabriecastello @JorgeM

I revited the original coding and am getting a syntax error on

 data: {action: add, id: <?php echo $id; ?> },

I changed this to:

data: {action: add, id:$("#id").val() },

and now the error is
ReferenceError: add is not defined

data: {action: add, id:$("#id").val() },
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.