I've just build shopping cart here
The add to cart button work perfectly adding the product to the cart without refreshing the entire page.
My question is, how to make the basket update the content after hit the add to cart link without refresh the pages
I have code to handle adding a product to the cart and to show the cart content.
<?php
if($what=="addtocart")
{
if ($cart)
{
$cart .= ','.$_GET['product_id'];
}
else
{
$cart = $_GET['product_id'];
}
$_SESSION['cart'] = $cart;
}
echo writeShoppingCart();
?>
and here are the writeShoppingCart() function
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
echo "<table class=table cellpadding=5 cellspacing=0 width=87% border=0>";
echo "<tr class=bold>";
echo "<td width=65>ID Product</td>";
echo "<td>Pattern</td>";
echo "<td>Inst Type</td>";
echo "</tr>";
include "config.php";
global $dbhost,$dbusername,$dbpassword;
$id_mysql = mysql_pconnect($dbhost,$dbusername,$dbpassword);
mysql_select_db($dbname, $id_mysql);
$cart = $_SESSION['cart'];
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
foreach ($contents as $id=>$qty) {
$view2 = "SELECT * FROM $table_product WHERE id='$id'";
$result2 = mysql_query($view2);
while
($baris=mysql_fetch_row($result2))
{
echo "<tr>";
echo "<td>$baris[1]</td>";
echo "<td>$baris[2]</td>";
echo "<td>$baris[3]</td>";
echo "</tr>";
}
}
echo "</table>";
echo "<span class=\"go_cart\">» View Complete Basket</span>";
}
}
is there any clue to make the echo writeShoppingCart(); reload after adding a product to the cart?
you forgot to add session_start() after opening your <?php tag
so I think you're referencing an empty variable when you do this: $_SESSION['cart'] = $cart;
$_SESSION['cart'] stays empty
to use the session variable you ALWAYS have to put session_start right at the top of the page;
<?php session_start();
//your stuff here
?>
I just checked your page out now and I noticed you're working within wordpress, wordpress doesn't support using session variables, so you'll have to look for the page in your theme that receives first control, it's usually the header.php inside your theme directory: /yourroot/wp-content/themes/yourthemename/header.php, you'll have to add the code above right at the top of that page.
also: I alerted the resp returned from the "add-link" and it returns an entire webpage, the php script you call should be outside of wordpress, prefereably in a file you access directly, so that when the result is returned you have only the output of the function you're echo-ing
Please comment if you're still having errors
//code to dynamically change item table;
$(document).ready(function(){
$('a#add-link').bind("click", function(event) {
event.preventDefault();
var url = $(this).attr("href");
$.get(url, function (resp) {
jAlert('Product Has Been Added to Shopping Cart');
//to do the following you have to put your shoppingcart table in a div with the id="shoppingcart"
$("#shoppingcart").html(resp)
});
});
});
PS: because I think you'll forget about this since I'm doing all your code for you.
right now your post page: "http://ksul.kittenpile.com/product.php" is return an entire webpage, which you will notice if you add the line alert(resp); above your jAlert() function.
It shouldn't return an entire webpage, so it shouldn't be printed to the browser the same way your other pages are printed! only the result of writeShoppingCart() should be echoed and NOTHING ELSE!
Related
I need my cart page to show a summary "line item" like view of all vending machines purchased on my vend page with $_SESSION['cart']
Here is my code which allows me to add multiple items to the cart: (Vend Page)
session_start();
//Check if $_SESSION['cart] exists
if (!isset($_SESSION['cart'])) {
//initiate cart as empty array
$_SESSION['cart'] = [];
}
if (isset($_POST['add'])) {
//add product id to session cart
$_SESSION['cart'][$_POST['add']] =1;
}
else if (isset($_POST['remove'])) {
//remove product id from session cart
unset($_SESSION['cart'][$_POST['remove']]);
}
I just need a way to display the items I "Add to Cart" on the Vend Page" to display in a list onto another page "Cart page". Ive made an image to show how it should be displayed: HERE
in your cart page add this -
session_start();
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $name => $price){
echo $name . " - " . $price;
}
}else{
// optional(if cart is empty it will redirect to another page)
header("location:products.php");
}
something like
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $name => $price){
echo $name . " - " . $price;
}
}
I have a simple php checkout but when adding the product to basket i get the following error:
PHP Notice: Undefined offset: 36 in C:\inetpub\wwwroot\shopping\cart.php on line 76
If i then refresh the page or go back to add another product it displays a product fine, it seems to be when adding to first product to the cart we get this error. any help would be much appreciated as all the answers i have tried have not worked.
<?php
// connect to the database
include("databasedrop.php");
?>
<div class="post">
<h2>Shopping Basket<span class="title-bottom"> </span></h2>
</div>
<!-- End Post -->
<?php
if (empty($_GET['id'])) {
$_GET['id'] = "";
}
$ProductID = $_GET['id']; //the product id from the URL
$action = $_GET['action']; //the action from the URL
//if there is an product_id and that product_id doesn't exist display an error message
switch ($action) { //decide what to do
case "add":
$_SESSION['cart'][$ProductID] ++; //add one to the quantity of the product with id $product_id
break;
case "remove":
$_SESSION['cart'][$ProductID] --; //remove one from the quantity of the product with id $product_id
if ($_SESSION['cart'][$ProductID] == 0)
unset($_SESSION['cart'][$ProductID]); //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 (empty($_SESSION['cart'])) {
$_SESSION['cart'] = "";
}
if ($_SESSION['cart']) { //if the cart isn't empty
//show the cart
echo "<table border=\"1\" padding=\"3\" width=\"40%\">"; //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 $ProductID => $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
if ($stmt = $conn->prepare("SELECT * FROM products WHERE ProductID=?")) {
$stmt->bind_param("i", $ProductID);
$stmt->execute();
$stmt->bind_result($ProductID, $Title, $Description, $Price, $Stock, $Image, $Category, $Status);
$stmt->fetch();
// show the form
}
$total = "";
$line_cost = $Price * $quantity; //work out the line cost
$total = $total + $line_cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">$Title</td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\">$quantity X</td>";
echo "<td align=\"center\">$line_cost</td>";
echo "</tr>";
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\">Total</td>";
echo "<td align=\"right\">$total</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\">Empty Cart</td>";
echo "</tr>";
echo "</table>";
} else {
//otherwise tell the user they have no items in their cart
echo "You have no items in your shopping cart.";
}
?>
Shot in the dark, but only solution I can see.
Do you ever create the $_SESSION['cart']-array?
Try this:
switch ($action) {
case "add":
if (!isset($_SESSION['cart'][$ProductID])) {
$_SESSION['cart'][$ProductID] = 1;
}
else {
$_SESSION['cart'][$ProductID]++;
}
break;
I am having trouble with a mini shopping cart. I have created the mini shopping cart and when a product is added it goes into the Basket page. However, i want to create a checkout page. How do i grab the products in the basket and put it in a checkout page.
So For example, the check out page will look like this
ITEM NAME, ITEM MODEL, ITEM PRICE
TOTAL OF ITEMS
CHECKOUT BUTTON (links to a payment system)
This is my Basket.php code:
<?php
$bikecode = $_GET['id']; //the product id from the URL
$action = $_GET['action']; //the action from the URL
if($bikecode && !productExists($bikecode)) {
die("Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$bikecode]++; //add one to the quantity of the product with id $bikecode
break;
case "remove":
$_SESSION['cart'][$bikecode]--; //remove one from the quantity of the product with id $bikecode
if($_SESSION['cart'][$bikecode] == 0) unset($_SESSION['cart'][$bikecode]); //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;
}
if($_SESSION['cart']){
echo "<table width=\"100%\">";
foreach($_SESSION['cart'] as $bikecode => $quantity) {
$sql = sprintf("SELECT BikeCode, Model, Price FROM Bike WHERE BikeCode = '%s';", $bikecode);
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0) {
list($bikecode, $model, $price) = mysqli_fetch_row($result);
$cost = $quantity * $price;
$total = $total + $cost;
echo "<tr><th>BikeCode:</th><th>Model:</th><th>Quantity:</th><th>Price:</th></tr>";
echo "<tr>";
echo "<td align=\"center\">$bikecode</td>";
echo "<td align=\"center\">$model</td>";
echo "<td align=\"center\">$quantity X</td>";
echo "<td align=\"center\">£$cost</td>";
echo "</tr>";
}
}
echo "<tr>";
echo "<td colspan=\"3\" align=\"right\">Total</td>";
echo "<td align=\"right\">£$total</td>";
echo "</tr>";
echo "<tr>";
echo "<td colspan=\"4\" align=\"right\">Empty Cart</td>";
echo "</tr>";
echo "</table>";
}else{
echo "You have no items in your shopping cart.";
}
function productExists($bikecode) {
$sql = sprintf("SELECT * FROM Bike WHERE BikeCode = '%s';", $bikecode);
return mysqli_num_rows(mysqli_query($con, $sql)) > 0;
}
?>
As long as you have a session_start(); on top of every page you should be able to use the exact same foreach loop as you do in this piece of coding. The session with the information would just be carried over to the next page.
Assume you have a page called test.php with the following code:
<?php
session_start();
$_SESSION['test'] = 1;
echo $_SESSION['test'];
?>
Then to access the test variable in othertest.php page,simply do the following:
<?php
session_start();
echo $_SESSION['test']; ?>
You forgot to add session_start() to the top of your php file. I recommend adding session_start() to a separate file and then including that file in each of the php pages that uses session variables.
Basically by clicking the "comment" link the last result of the query should show and by clicking again it should be hidden. I have tried Rocket's code as well but I get an error message in the bottom of the browser and when I click "comments" it just takes me to the top of the page. I would apprieciate some advice on this
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
This is a loop, echoing the same thing over and over, thus making all the divs have the same ID, something2.
IDs need to be unique, you gonna have to make unique IDs for each div.
Something like: <div id='something$i' style='display: none;'> (remembering to increment $i).
Also, you're gonna to escape the quotes in your onclick attribute.
<a href='#' onclick=\"toggle_visibility('something$i');\">
The code should look something like this:
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
Escape the quotes :
$blah = "onclick='toggle_visibility(\"something2\");'>Comments</a>"
There is an easier way to hiding / showing the next sibling ....
try this
<div style="display:none">some hidden content</div>
function toggle(el,ev) {
ev.preventDefault(); // prevent the link from being followed
el = next(el); // get the next element
if (el.style.display == "none") { // toggle the display
el.style.display = "block";
} else {
el.style.display = "none";
}
}
/*
Credit to John Resig for this function
taken from Pro JavaScript techniques
*/
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
Working example
You can throw in a counter into your code as the while loop is executing to dynamically generate unique id's for each comment div. Or, you can pull a unique field out of the query result for the id's, as long as you hook up to it appropriately later if it ends up being used and remain consistent in the rest of the code.
either
$count = count($result);
...
while (...){
$count--;
echo '... id="something'. $count .'" ...'
}
or...
while (...){
echo '... id="something'. $row['ID'] .'" ...'
}
I have a problem when using jQuery Post, the PHP returns all the HTML of the page up to the newly created HTML, rather then just the HTML that is output by the PHP.
As an example say the php outputs: '<div>Some Content</div>'
Then the jQuery Post returns: '<html><head>...all the head content...</head><body>...other content...<div>Some Content</div>'
Here's the jQuery (link to full code: http://pastebin.com/U7R8PqX1):
jQuery("form[ID^=product_form]").submit(function() {
var current_url = js_data.current_url;
form_values = jQuery(this).serialize();
jQuery.post(current_url+"?ajax=true", form_values, function(returned_data) {
jQuery('div.shopping-cart').html(returned_data);
}
});
return false;
});
And here's the PHP (version 5.3.6 - link to full code: http://pastebin.com/zjSUUbmL):
function output_cart()
{
ob_start();
echo $this->output_cart_html();
$output = ob_get_contents();
ob_end_clean();
echo $output;
exit();
}
function output_cart_html() {
if (!isset($_SESSION['cart_items']))
{
$output = '<div class="cart_content faded">BASKET - Empty</div>';
return $output;
} else {
$total_items = 0;
$total_items = 0;
$items_in_cart = $_SESSION['cart_items'];
// work out total price and total items
foreach ($items_in_cart as $item_in_cart) {
$total_items += $item_in_cart['quantity'];
$total_price += floatval($item_in_cart['updated_price']*$item_in_cart['quantity']);
}
$template_url = get_bloginfo('template_directory');
$output = '';
$output_price = $dp_shopping_cart_settings['dp_currency_symbol'].number_format($total_price,2);
if($total_items == 1){ $item_text = ' Item'; } else { $item_text = ' Items'; }
$output .= $total_items . $item_text;
$output .= ' <span class="bullet"></span> Total '.$output_price;
// empty cart btn
$output .= '<form action="" method="post" class="empty_cart">
<input type="hidden" name="ajax_action" value="empty_cart" />
<span class="emptycart"> <img src="'.$template_url.'/images/empty.png" width="9" height="9" title="Empty Your Items" alt="Empty Your Items" />Empty Your Cart</span>
</form>';
// check out btn
$output .= ' <span class="bullet"></span> <span class="gocheckout">'.$this->output_checkout_link().' </span>';
return $output;
}
}
You need to check if the form has been posted yet with the PHP. To do this, just check if the 'ajax' parameter is there, or send another $_GET variable if you wish (by adding &anotherparementer=1 to the end of the jQuery post URL). Example:
<?php
if(isset($_GET['ajax'])) {
//your PHP code here that submits the form, i.e. the functions that you have, etc.
}
else {
?>
<html>
<head>
head content here...
</head>
<body>
body content here...
</body>
</html>
<?php
}
?>
I hope this helps.
Ok it turns out my problem was with the way Wordpress processes AJAX requests. The plugin I was building on top of was using AJAX but didn't have these issues (I'm not sure why maybe because they were using eval), so I hadn't realised there was a correct way of using AJAX with Wordpress. Here's a bunch of information if anyone else has similar problems:
http://codex.wordpress.org/AJAX_in_Plugins
http://byronyasgur.wordpress.com/2011/06/27/frontend-forward-facing-ajax-in-wordpress/
(this one really helped me out, a very simple example that I was able to adapt)
-- sorry I couldn't post more links because I'm too new on this site, but check out the links at the bottom of the first link above, especially the '5 Tips'.
As I'm using classes I instantiated the class from the index file of my plugin with this:
if ($_POST['action'] === 'action_name') {
$class_obj = new \namespace_name\class();
add_action('wp_ajax_action_name', array($class_obj, 'method_name'));
add_action('wp_ajax_nopriv_action_name', array($class_obj, 'method_name'));
}