Add to Cart button always redirect me to my cart

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
adsegzy
Forum Contributor
Posts: 184
Joined: Tue Jul 28, 2009 9:26 am

Add to Cart button always redirect me to my cart

Post by adsegzy »

Hello there, am having an online store with cart, but anytime ADD TO CART button is clicked, insteasd of the items to be added to the cart and the visitor still remain on the page, the product will be added to the cart and the visitor will be redirected to the cart. I want the visitor to remain on the page after adding product to the cart exept if he want to view the cart, then he can click VIEW CART BUTTON.

This is my ADD TO CART FORM
<form name="form<?php echo $id; ?>" method="post" action="">
Qty:
<select name="many" id="many" class="input">
<option value="1" style="padding:2px 10px;">1</option>
<option value="2" style="padding:2px 10px; background:#F0F0F0;">2</option>
<option value="3" style="padding:2px 10px;">3</option>
<option value="4" style="padding:2px 10px; background:#F0F0F0;">4</option>
<option value="5" style="padding:2px 10px;">5</option>
</select>
<input type="hidden" name="id" id="id" value="<?php echo $id; ?>" />
<input type="image" src="images/add-to-cart.png" name="submit" />
</form>
Below is my cart script.

Code: Select all

    <?php
    ob_start();
    include_once("includes/dbinfo.php");
    include_once("my_cart.php");
    ?>
    <?php
    ////////////////////////////////////////////////////////
    // SECTION 1 (when the member wants to add a product to the cart from the product list)
    ////////////////////////////////////////////////////////
    if(isset($_POST[id])){
    	$id = $_POST[id];
    	$quantity = $_POST[many];
    	$wasFound = false;
    	$i = 0;
    	
    	//if the cart session variable is not set or cart is empty
    	if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"])<1){
    	
    	//run if the cart is empty or not set
    	$_SESSION["cart_array"] = array(0=>array("item_id"=>$id, "quantity"=>$quantity));
    	
    	}else{
    	//run if the cart has at least one item in it
    		foreach($_SESSION["cart_array"] as $each_item){
    			$i++;
    			while(list($key,$value)=each($each_item)){
    				if($key=="item_id" && $value == $id){
    					//that item is in cart already so let's adjust its quantity using array_splice()
    					array_splice($_SESSION["cart_array"], $i-1,1,array(array("item_id"=>$id, "quantity"=>$each_item["quantity"]+$quantity)));
    					$wasFound = true;
    				}
    			}
    		}
    		
    		// to add a new item to the cexisting items in the art
    		if($wasFound==false){
    			array_push($_SESSION["cart_array"], array("item_id"=>$id, "quantity"=>$quantity));
    		}
    	}
    	header("location:cart.php");
    	exit();
    }
    ?>
    <?php
    ////////////////////////////////////////////////////////
    // SECTION 2 (if the user decide to empty the cart)
    ////////////////////////////////////////////////////////
    
    if(isset($_GET['cmd']) && $_GET['cmd'] == "emptycart"){
    	unset($_SESSION["cart_array"]);
    }
    ?>
    <?php
    ////////////////////////////////////////////////////////
    // SECTION 3 (if the user decide to adjust quantity)
    ////////////////////////////////////////////////////////
    if(isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != ""){
    		$item_to_adjust = $_POST['item_to_adjust'];
    		$quantity = $_POST['quantity'];
    		$i = 0;
    		foreach($_SESSION["cart_array"] as $each_item){
    			$i++;
    			while(list($key,$value)=each($each_item)){
    				if($key=="item_id" && $value == $item_to_adjust){
    					//that item is in cart already so let's adjust its quantity using array_splice()
    					array_splice($_SESSION["cart_array"], $i-1,1,array(array("item_id"=>$item_to_adjust, "quantity"=>$quantity)));
    				
    				}
    			}
    		}
    }
    ?>
    <?php
    ////////////////////////////////////////////////////////
    // SECTION 4 (the member wants to remove a product)
    ////////////////////////////////////////////////////////
    if(isset($_POST['index_to_remove']) && $_POST['index_to_remove']!=""){
    	//access the array and run code to remove that array index
    	
    	$key_to_remove = $_POST['index_to_remove'];
    	if(count($_SESSION["cart_array"])<=1){
    			unset($_SESSION["cart_array"]);
    	}else{
    			unset($_SESSION["cart_array"]["$key_to_remove"]);
    			sort($_SESSION["cart_array"]);
    	}
    	header("location:cart.php");
    	exit();
    }
    ?>
    <?php
    ////////////////////////////////////////////////////////
    // SECTION 5 (render the cart for the user to view)
    ////////////////////////////////////////////////////////
    
    $cartOutput =="";
    $cartTotal =="";
    $sideCart =="";
    $mailCart =="";
    
    if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"])<1){
    	$cartOutput = "<p>&nbsp;</p><p><h2 align='center'>Your Shopping Cart is empty.</p>&nbsp;<p></p></h2>";
    }else{
    		
    		$i = 0;
    		$j = 0;
    		$m = 0;
    		foreach($_SESSION["cart_array"] as $each_item){
    			$number++;
    			$item_id = $each_item["item_id"];
    			$sql = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 1");
    			$listing = 1;
    			while($roll=mysql_fetch_array($sql)){
    			$id=stripslashes($roll[id]);
    			$product=stripslashes($roll[product]);
    			$type=stripslashes($roll[type]);
    			$name=stripslashes($roll[name]);
    			$facts=stripslashes($roll[facts]);
    			$detail=stripslashes($roll[detail]);
    			$ingredients=stripslashes($roll[ingredients]);
    			$how=stripslashes($roll[how]);
    			$price=stripslashes($roll[nprice]);
    			$qty=stripslashes($roll[qty]);
    			}
    			$totalPrice2 = $price * $each_item['quantity']; //price times quantity.
    			
    			$cartTotal = $totalPrice2 + $cartTotal; //sum up all the prices in the cart to give grand amount.
    
    			//putting all prices into naira format.
    			$price = "#".number_format($price, '00','.',',').".00";
    			$totalPrice = "#".number_format($totalPrice2, '00','.',',').".00";
    			
    			$get_imgs = mysql_query("SELECT * FROM imgs WHERE pid='$id' && status='m'");
    			$rows = mysql_fetch_array($get_imgs);{
    			$spix = $rows[spix];
    			$bpix = $rows[bpix];
    			}
    			
    			if($spix!="") $img = "<img src='imgs/products/$spix' height='70' class='cart_img' />";
    			else $img = "<img src='images/product.png' height='70' class='cart_img' align='left' />";
    					
    			//dynamic rows assembly
    			$cartOutput.="<tr>";
    			$cartOutput.="<td align='center' valign='top' style='border-bottom:1px solid #ccc'>".$number."</td>";
    			$cartOutput.="<td align='left' valign='top' style='border-bottom:1px solid #ccc'><a href='counter.php?pid=$id'>$img".$name."</a></td>";
    			$cartOutput.="<td align='center' valign='middle' style='border-bottom:1px solid #ccc'><form action='cart.php' method='post'>
    			<input type='image' src='images/remove-from-cart.png' name='deleteBtn".$item_id."' /><input name='index_to_remove' type='hidden' value='".$i."' /></form></td>";
    			$cartOutput.="<td align='center' valign='middle' style='border-bottom:1px solid #ccc'>
    			<form action='cart.php' method='post'>
    			<input name='quantity' type='text' size='1' maxlength='2' value='".$each_item['quantity']."' />
    			<input name='adjustBtn".$item_id."' type='submit' value='Adjust' />
    			<input name='item_to_adjust' type='hidden' value='".$item_id."' />
    			</form></td>";
    			$cartOutput.="<td align='centre' valign='middle' style='border-bottom:1px solid #ccc'>".$price."</td>";
    			//$cartOutput.="<td align='center' valign='middle' style='border-bottom:1px solid #ccc'>".$each_item['quantity']."</td>";
    			$cartOutput.="<td align='right' valign='middle' style='border-bottom:1px solid #ccc'>".$totalPrice."</td>";
    			$cartOutput.="</tr>";
    			$i++;	
    		}
    		
    }
    ?>
Pls where is the error or which better script can i use. Thanks
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Add to Cart button always redirect me to my cart

Post by Celauran »

Why not attach a listener to the submit button and have the cart updated asynchronously?
adsegzy
Forum Contributor
Posts: 184
Joined: Tue Jul 28, 2009 9:26 am

Re: Add to Cart button always redirect me to my cart

Post by adsegzy »

I dont know how to do that, can you please put me through, or any script/post around that does that?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Add to Cart button always redirect me to my cart

Post by Celauran »

Give your form an ID, attach a jQuery listener to the submit function which will submit the form data to be processed in the background without redirecting the user. Take a look at jQuery.ajax()

Code: Select all

$('#your-form-id').submit(function(e) {
	e.preventDefault();
	$.ajax({
		url: some-page.php,
		data: $(this).serialize()
	})
	.done(function(data, status, request) {
		// do something
	})
	.error(function(request, status, error) {
		// handle error here
	})
});
Post Reply