How do I add variables in javascript and php?

sofuscomer
sofuscomer used Ask the Experts™
on
Dear folks
I have downloaded a very nice and easy tutorial from a guy called Richard Clark.
http://www.qualitycodes.com/tutorial.php?articleid=25&title=Tutorial-Building-a-shopping-cart-in-PHP

I got it all up and running on my site: http://www.sofuscomer.com/shopping

Its all working. But I wish to add a select field on the products.php page that shows a dropdown of choices, that may change the price of the image added to the cart. This is not included in the tutorial, so I have tried to include it myself. Please look at the bold code, cause this is where I think I have to change some code or add some lines to make it add the selected priceid from the select dropdown. I am really new at javascript and $_SESSION coding.

Below is the current code (Modified paths and mysql tables for security).
Below that is the code for the functions.php
And finally the code for the shoppingcart.php

products.php

 <?php
include_once "path/db.php";
include_once "path/functions.php";

[b]if ($_REQUEST['command']=='add' && $_REQUEST['productid']>0) {
	$pid=$_REQUEST['productid'];
	addtocart($pid, 1);
	header("location:shoppingcart.php");
	exit();
}
$priceid=$REQUEST['priceid'];[/b]
?>
<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
    <title>Photojournalist and webdesigner Sofus Comer - Thy, Denmark</title>
	<link href="../stylesheet.css" rel="stylesheet" type="text/css" media="only screen and (min-width:961px)" />
	<!-- iphone -->
	<link href="../iphone.css" rel="stylesheet" type="text/css" media="only screen and (max-width:960px)">
	[b]<script language="javascript">
	function addtocart(pid,priceid){
		document.form1.productid.value=pid;
		document.form1.priceid.value=priceid;
		document.form1.command.value='add';
		document.form1.submit();
	}
	</script>[/b]
</head>
<body>
<div class="div_master">
<div class="titlediv">Photojournalist Sofus Comer</div>
<?php
include_once "../menu_includes/menu_main.php";
?>
<div class="descript"></div>
<div class="div_main">
<div class="page_right">
    <div class="portfolio_view_title">Ordering Prints</div>
    <div class="photostreamExif"></div>
    <div class="clear"></div>
    </div>
    <div class="page_master">
<form name="form1">
	<input type="hidden" name="productid" />
    <input type="hidden" name="command" />
	<table border="0" cellpadding="2px" width="auto">
		<?php
$result=mysql_query("select * from sometable WHERE ids = 630 ORDER BY ids DESC LIMIT 100");
while ($row=mysql_fetch_array($result)) {
?>
    	<tr>
        	<td><img src="../path_to_images/somemore_<?php echo $row['idf']?>.jpg" class="img_border_white"/></td>
            <td><b>Image ID: <?php echo $row['ids'];?>_<?php echo $row['idf'];?>_<?php echo $row['image']?></b>
            <br />
            <?php echo $row['caption']?>
            <br />

                    	Price:<big style="color:green">
       [b] <select name="priceid" id="priceid">
				<option value="1">A4 (With 1,2cm white border)</option>
				<option value="2">A3 (With 1,2cm white border)</option>
				<option value="3">A3+ (With 1,2cm white border)</option>
				<option value="4">A2 (With 1,2cm white border)</option>
				<option value="5">A2 (Borderless)</option>
		</select>[/b]
		</form>
		</big>

                    	<br /><br />
                    <input type="button" value="Add to cart" onclick="addtocart(<?php echo $row['idf']?>)" />
			</td>
		</tr>
        <tr><td colspan="2"><hr size="1" /></td>
        <?php } ?>
    </table>
</div>
</div>
</div>
</div>
</body>
</html>

Open in new window


functions.php

<?php
	function get_product_name($pid){
		$result=mysql_query("select idf,image,ids from tablename where idf=$pid");
		$row=mysql_fetch_array($result);
		return $row['ids']."_".$row['idf']."_".$row['image'];
	}
	[b]function get_price($priceid){
		$result=mysql_query("select price from printpricesandoptions where id=$priceid");
		$row=mysql_fetch_array($result);
		return $row['price'];
	}[/b]
	function remove_product($pid){
		$pid=intval($pid);
		$max=count($_SESSION['cart']);
		for($i=0;$i<$max;$i++){
			if($pid==$_SESSION['cart'][$i]['productid']){
				unset($_SESSION['cart'][$i]);
				break;
			}
		}
		$_SESSION['cart']=array_values($_SESSION['cart']);
	}
	function get_order_total(){
		$max=count($_SESSION['cart']);
		$sum=0;
		for($i=0;$i<$max;$i++){
			$pid=$_SESSION['cart'][$i]['productid'];
			$q=$_SESSION['cart'][$i]['qty'];
			$price=get_price($priceid);
			$sum+=$price*$q;
		}
		return $sum;
	}
	function addtocart($pid,$q){
		if($pid<1 or $q<1) return;
		
		if(is_array($_SESSION['cart'])){
			if(product_exists($pid)) return;
			$max=count($_SESSION['cart']);
			$_SESSION['cart'][$max]['productid']=$pid;
			$_SESSION['cart'][$max]['priceid']=$price;
			$_SESSION['cart'][$max]['qty']=$q;
		}
		else{
			$_SESSION['cart']=array();
			$_SESSION['cart'][0]['productid']=$pid;
			$_SESSION['cart'][0]['priceid']=$price;
			$_SESSION['cart'][0]['qty']=$q;
		}
	}
	function product_exists($pid){
		$pid=intval($pid);
		$max=count($_SESSION['cart']);
		$flag=0;
		for($i=0;$i<$max;$i++){
			if($pid==$_SESSION['cart'][$i]['productid']){
				$flag=1;
				break;
			}
		}
		return $flag;
	}

?>

Open in new window



shoppingscart.php

<?php
	include("path/db.php");
	include("path/functions.php");


	if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0){
		remove_product($_REQUEST['pid']);
	}
	else if($_REQUEST['command']=='clear'){
		unset($_SESSION['cart']);
	}
	else if($_REQUEST['command']=='update'){
		$max=count($_SESSION['cart']);
		for($i=0;$i<$max;$i++){
			$pid=$_SESSION['cart'][$i]['productid'];
			$q=intval($_REQUEST['product'.$pid]);
			if($q>0 && $q<=999){
				$_SESSION['cart'][$i]['qty']=$q;
			}
			else{
				$msg='Some products not updated!, quantity must be a number between 1 and 999';
			}
		}
	}

?>

Open in new window


And in the <head>
<script language="javascript">
	function del(pid){
		if(confirm('Do you really mean to delete this item')){
			document.form1.pid.value=pid;
			document.form1.command.value='delete';
			document.form1.submit();
		}
	}
	function clear_cart(){
		if(confirm('This will empty your shopping cart, continue?')){
			document.form1.command.value='clear';
			document.form1.submit();
		}
	}
	function update_cart(){
		document.form1.command.value='update';
		document.form1.submit();
	}


</script>

Open in new window


Thanks a lot anybody who can assist me here.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Where is the $price coming from in the addtocart function?

Author

Commented:
I put it there to see if it worked.
Am not sure if its needed?

I think i narrowed it down to making it all work on the functions.php page.

What I cant seem to figure out is on the products.php page
I want to add a variable to the addtocart function that is sent to the function get_price on the functions.php This variable i am calling $priceid.

Cause if I manually enter a number (Example) id=1, or id=3 instead of id=$priceid
I get the result I am looking for. My priceis collected from the database and the price is entered in the shopping basket.

So the way I see it. Somewhere in this code from the products.php page lies the solution.
What do I possible need to add for the addtocart function that I am calling in the submit for it to pass both $pid and $priceid to the functions.php page.
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
Well it is not going to work because it is not being set anywhere - hence my question - it was not clear if it was your code or from the tutorial.

What you need to do is pass the price value through to the addtocart function

addtocart($id, $q, $priceid)

That way when you make the assignment with $price there is a value there.

in your <b> section above add $priceid = $_REQUEST['priceid']) before the call to addtocart

Then put the priceid in the call to addtocart

Modify the addtocart function to accept the priceid field

This next bit depends on whether you are storing the priceid in the cart or just the price.
If the priceid is being stored then you can just set the cart[$max]['priceid'] field to the passed in $priceid value. If not you will need to call get_price to get the price and then assign cart[$max]['priceid'] to the returned value;
Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

Commented:
Hi JulianH
Thanks. Still havent figured it out yet.

When you say

"Modify the addtocart function to accept the priceid field"

Do you mean this part in the products.php page?

<script language="javascript">
	function addtocart(pid,priceid){
		document.form1.productid.value=pid;
		document.form1.priceid.value=priceid; 
		document.form1.command.value='add';
		document.form1.submit();
	}
	</script>

Open in new window


Or

is it this in the top of the products page?

if ($_REQUEST['command']=='add' && $_REQUEST['productid']>0) {
	$priceid=$REQUEST['priceid'];
	$pid=$_REQUEST['productid'];
	addtocart($pid, 1,$priceid);
	header("location:shoppingcart.php");
	exit();
}

Open in new window


OR this in the functions.php page?

      
function addtocart($pid,$q,$priceid){
		if($pid<1 or $q<1) return;
		
		if(is_array($_SESSION['cart'])){
			if(product_exists($pid)) return;
			$max=count($_SESSION['cart']);
			$_SESSION['cart'][$max]['productid']=$pid;
			$_SESSION['cart'][$max]['qty']=$q;
			$_SESSION['cart'][$max]['priceid']=$priceid;
		}
		else{
			$_SESSION['cart']=array();
			$_SESSION['cart'][0]['productid']=$pid;
			$_SESSION['cart'][0]['qty']=$q;
			$_SESSION['cart'][0]['priceid']=$priceid;
		}
	}

Open in new window

Author

Commented:
To answer your question regarding if its the id or the price i am storing. I want to store the id, so I can show a more detailed shopping cart. Like price, bordersize, printsize.
Principal Data Engineer
Commented:
Hi sofuscomer

We should be able to sort this out pretty quickly. I've just skimmed through your code and although it's not the way I would recommend to build a shopping cart it certainly should work.

In your original code you post there is a function in the file "functions.php"... this one:

function addtocart($pid,$q){
            if($pid<1 or $q<1) return;
            
            if(is_array($_SESSION['cart'])){
                  if(product_exists($pid)) return;
                  $max=count($_SESSION['cart']);
                  $_SESSION['cart'][$max]['productid']=$pid;
                  $_SESSION['cart'][$max]['priceid']=$price;
                  $_SESSION['cart'][$max]['qty']=$q;
            }
            else{
                  $_SESSION['cart']=array();
                  $_SESSION['cart'][0]['productid']=$pid;
                  $_SESSION['cart'][0]['priceid']=$price;
                  $_SESSION['cart'][0]['qty']=$q;
            }
      }

the lines that reference $price will not do anything. You have not passed any $price variable or value into that function. What you need if you want to store the priceid in place of the price, is to name your variables accordingly (so they are easier to understand). $price should be $priceid. The function is expecting only two arguments at this time ( $pid & $q )

There is no $price or $priceid so the first step was to modify that function to accept a price ID not a price.

function addtocart($pid,$q, $priceid){
            if($pid<1 or $q<1) return;
            
            if(is_array($_SESSION['cart'])){
                  if(product_exists($pid)) return;
                  $max=count($_SESSION['cart']);
                  $_SESSION['cart'][$max]['productid']=$pid;
                  $_SESSION['cart'][$max]['priceid']=$priceid;
                  $_SESSION['cart'][$max]['qty']=$q;
            }
            else{
                  $_SESSION['cart']=array();
                  $_SESSION['cart'][0]['productid']=$pid;
                  $_SESSION['cart'][0]['priceid']=$priceid;
                  $_SESSION['cart'][0]['qty']=$q;
            }
      }

Now on line 6 of your very top code which is the page that the form is on, it will receive data once the form is submitted but you are not sending the priceid from the form. So, first you need to add a line (right after 6 will do) so php knows what the priceid is.

$priceid=$_REQUEST['priceid'];

Line 7 should be modified so it sends the priceid

addtocart($pid, 1); should be addtocart($pid, 1, $priceid);


Line 34 in functions.php needs modifying

function addtocart($pid,$q){      should be

function addtocart($pid,$q, $priceid){


Change line 35 from if($pid<1 or $q<1) return; to if($pid < 1 || $q < 1 || !isset($priceid)) return;


It helps to read your code if you space the characters and we don't use "and" or "or" these days it is shortcutted to "&&" and "||"

Ok back to the task....

Lines 41 and 47 you need to change $price to $priceid (in functions.php)

That should get things rolling along for you.. Try those changes and see if you have any luck.

Author

Commented:
Hi Elvin
I tried all your suggestions and thanks a lot.
But still not working, and it was way over my head on several areas.
So I have initiated another solution, that also makes so much more sense in all this.

Not to pass anything but the id of the product, and on the shoppingcart page, offer more options there. That meant less sending of data.
Example on my website

I wish to grant you and JulianH half points each for your good attempts.

Can this be done in any way?
Atb Sofus

Author

Commented:
There was no solution to this Q. I set out with a cramped scenario and changed directions, which makes this Q uninteresting.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
In response to your questions elven66 explained what I meant.
Mark BradyPrincipal Data Engineer

Commented:
I'm wondering why I got a 'C' grade for my assist? C means the answer I provided was not very good but merely a few points for effort. My answer was spot on the mark. I am a senior developer and have had many years in this game. If something is over the authors understanding (over their heads) that should be no reason to award a poor grade to the expert. Not to worried about it but for future reference you should only award a C grade if the answer is ambiguous or very hard to follow for the normal programmer (Not a newbie with little understanding). Thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial