Avatar of sofuscomer
sofuscomerFlag for Denmark

asked on 

How do I add variables in javascript and php?

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.
JavaScriptPHPMySQL Server

Avatar of undefined
Last Comment
Mark Brady
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Where is the $price coming from in the addtocart function?
Avatar of sofuscomer
sofuscomer
Flag of Denmark image

ASKER

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.
SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of sofuscomer
sofuscomer
Flag of Denmark image

ASKER

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

Avatar of sofuscomer
sofuscomer
Flag of Denmark image

ASKER

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.
ASKER CERTIFIED SOLUTION
Avatar of Mark Brady
Mark Brady
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of sofuscomer
sofuscomer
Flag of Denmark image

ASKER

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
Avatar of sofuscomer
sofuscomer
Flag of Denmark image

ASKER

There was no solution to this Q. I set out with a cramped scenario and changed directions, which makes this Q uninteresting.
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

In response to your questions elven66 explained what I meant.
Avatar of Mark Brady
Mark Brady
Flag of United States of America image

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
JavaScript
JavaScript

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and in almost every mainstream web browser.

127K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo