0

hey everyone, first i will show u my code pages.

addcart.php

<?php

require_once("../Connection/connection.php");

if(!$_POST['img']) die("There is no such product!");

$img=mysql_real_escape_string(end(explode('/',$_POST['img'])));
$q_result=mysql_query("SELECT * FROM tbl_items WHERE item_photo='".$img."'");
$row=mysql_fetch_assoc($q_result);

$period = $_POST['period'];
$count = $_POST['count'];


$query_search1 =("SELECT * FROM `tbl_rates` WHERE `rental_period` = 'Daily' AND `units` = '10' AND `category_id` = '1'");
$search1 = mysql_query($query_search1, $pcrent) or die(mysql_error());
$row_search1 = mysql_fetch_assoc($search1);

echo '{status:1,id:'.$row['itid'].',price:'.trim($row_search1['rate']).',txt:\'\
\
<table width="100%" id="table_'.$row['itid'].'">\
  <tr>\
    <td width="20%">'.$row['item_title'].'</td>\
    <td width="10%"><select name="'.$row['itid'].'_cnt" id="'.$row['itid'].'_cnt" onchange="change('.$row['itid'].');">\
	<option value=""></option>';
	
for($i=1; $i<=$row['item_quantity']; $i++)
{
  echo '<option value="'.$i.'">'.$i.'</option>';
}

echo '</select>\
        \</td>\
    <td width="15%"><select name="'.$row['itid'].'_due" id="'.$row['itid'].'_due" onchange="change('.$row['itid'].');">\
	<option value=""></option>\
  	<option value="Daily">Daily</option>\
	<option value="Weekly">Weekly</option>\
	<option value="Monthly">Monthly</option>\
	<option value="1Year">1Year</option>\
	<option value="2Years">2Years</option>\
	<option value="3Years">3Years</option>\
</select>\
        \
        </td>\
        <td width="15%"><a href="#" onclick="remove('.$row['itid'].');return false;" class="remove">Remove</a></td>\
  </tr>\
</table>\'}';
?>

script.js

var purchased=new Array();//an array containing all the products we've purcha
var totalprice=0;//the total price
var unit_price;
var asluprice;

$(document).ready(function(){
	
	
	$(".product_item img").draggable({// enable all product images to be dragged
	
	containment: 'document',
	opacity: 0.6,
	revert: 'invalid',
	helper: 'clone',
	zIndex: 100
	
	});

	$(".drop-here").droppable({// convert the shopping cart to a droppable
	
			drop:
					function(e, ui)
					{
						var param = $(ui.draggable).attr('src');
						 // IE6 fix
						if($.browser.msie && $.browser.version=='6.0')
						{
							param = $(ui.draggable).attr('style').match(/src=\"([^\"]+)\"/);
							param = param[1];
						}

						addlist(param);// the special addlist function - see below
						
					}
	});

});


function addlist(param)
{ // the addlist function ads a product to the shopping cart

	$.ajax({// sending an ajax request to addtocart.php
	type: "POST",
	url: "ajax/addtocart.php",
	data: 'img='+encodeURIComponent(param),// the product image as a parameter
	dataType: 'json',// expecting json
	beforeSend: function(x){$('#ajax-loader').css('visibility','visible');},// showing the loading gif
	success: function(msg){
		
		$('#ajax-loader').css('visibility','hidden');// hiding the loading gif animation
		if(parseInt(msg.status)!=1)
		{
			return false;// if there has been an error, return false
		}
		else
		{
			var check=false;
			var cnt = false;
			
			for(var i=0; i<purchased.length;i++)
			{
				if(purchased[i].id==msg.id)// find if we have already bought this prduct
				{
					check=true;
					cnt=purchased[i].cnt;
					
					break;
				}
			}
			
			if(!cnt)// if we haven't bought it yet, or we have removed it from the purchases, we insert it in the shopping cart
				$('#item-list').append(msg.txt);
				
			if(!check)// if we haven't bought it yet, insert it in the purchased array
			{
				purchased.push({id:msg.id,cnt:1,price:msg.price});
			}
			else  // else if we've bought it
			{
				if(cnt>=3) return false;// 3 products of type max
				
				purchased[i].cnt++;
				$('#'+msg.id+'_cnt').val(purchased[i].cnt);// update the select box
			}
			
			totalprice+=msg.price;// recalculate the price
			update_total();// update the total div
		}	
	}
	});
}

function findpos(id)// a helper function that finds the position at which the product is inserted in the array, returns the position
{
	for(var i=0; i<purchased.length;i++)
	{
		if(purchased[i].id==id)
			return i;
	}
	
	return false;
}

function remove(id)// remove a product from the shopping cart
{
	var i=findpos(id);// find its position in the array
	
	totalprice-=purchased[i].price*purchased[i].cnt;// recalculate the price
	purchased[i].cnt = 0;// reset the counter
	$('#table_'+id).remove();// remove it from the cart
	update_total();// update the total price counter on the page
}

function change(id)// evoked when we change the number of products via the select area
{
	var i=findpos(id);
	
		period=$('#'+id+'_due').val();
	count=$('#'+id+'_cnt').val();
	//alert(count);
	//alert(period);
	
if(count <= 10)
{
	unit_price = 10;
}
if(count > 10 && count <= 20)
{
	unit_price = 20;
}
if(count > 20 && count <= 30)
{
	unit_price = 30;
}
rate_call(period, unit_price);
//	alert(actual_rate);

	totalprice+=count-(purchased[i].cnt)*actual_rate;
	
	purchased[i].cnt=parseInt($('#'+id+'_cnt').val());
	asluprice = count*actual_rate;
	//alert(asluprice);
	update_total();

}


function rate_call(period, count)
{
	$.ajax({
	type: "POST",
	url: "ajax/ajax_query.php",
	data: 'period='+period+'&count='+count,
	dataType: 'text',
	async:false,
	success: function(rat){
		actual_rate = rat;
		
		}
 });
 return actual_rate;
}


function update_total()// function that updates the total price div on the page
{
	if(asluprice)
	{
		$('#total').html('total: RM '+totalprice);// if we've bought somehitng, show the total price div and the purchase button
		$('a.button').css('display','block');
		$('#cart-text').css('display','none');
	}
	else// hide them
	{
		$('#total').html('');
		$('a.button').hide();
		$('#cart-text').css('display','block');
	}
}

My problem is i want to update the totalprice div, when i change the value from the combo boxes. i just want to calculate the rate and the quantity and update it to the totalprice div. but now it is not working. i tried a lot and it has some problem. im retrieving the rate from a database using another php file shown in that script.js. all the values are retrieving and working fine. any one has any suggestion how to do this any other way, or have a fix for this.?? please help..

here is my cart image. its a drag and drop cart. i use ajax drag and drop care script there.
http://www.shainjetly.com/cart.png

5
Contributors
11
Replies
12
Views
6 Years
Discussion Span
Last Post by Taywin
0

period=$('#'+id+'_due').val();

if 'id' is a number, then it won't work. Adjust your tag id's with a leading letter/word.

For example:
<p id=32>my paragraph</p>
will cause problems with jquery. Instead use:

<p id=myParagraph32>my paragraph</p>

0

hi, thanks, as you can see that, my "period" variable doesnt have any problems.
it is like this. id is a number. out put wud be. #32_due. i can get the value of the combo box there. my problem is updating the total price div.

0

Could you give a scenario when the total becomes wrong? Need to know how it happens or it is difficult to look at the code only and determine where the bug is.

Also, in your 2nd code portion line 59, if you are going to use 'cnt' variable as integer, you should declare it as integer instead of boolean. Even though JavaScript is very loose in type, it could confuse yourself or others who read your code later on. Besides, it is a bad habit and may give you an unexpected result. In this similar situation, you use the 'cnt' in line 72. If you consider value integer '0' is valid for this condition (but you may not in this case), the check for if-statement will be false because JavaScript determines 'false' or '0' as false. Just to clarify...

Edited by Taywin: n/a

0

Could you give a scenario when the total becomes wrong? Need to know how it happens or it is difficult to look at the code only and determine where the bug is.

Also, in your 2nd code portion line 59, if you are going to use 'cnt' variable as integer, you should declare it as integer instead of boolean. Even though JavaScript is very loose in type, it could confuse yourself or others who read your code later on. Besides, it is a bad habit and may give you an unexpected result. In this similar situation, you use the 'cnt' in line 72. If you consider value integer '0' is valid for this condition (but you may not in this case), the check for if-statement will be false because JavaScript determines 'false' or '0' as false. Just to clarify...

Hi, thanks.
can you check the image in here. http://www.shainjetly.com/cart.png.
as u can see in the image the TOTLl price div there has a minus figure which is wrong.
the products are drag and drop which means, customers can drag and drop the products there.
everytime they drop the total must be clacualted. the duration which is monthly, daily etc.. has a fixed value. for example. when daily is selected it has a fixed value like 60. so it must be multiplied by the quantity there in the first combo box. so like that monthly is the same, exmple monthly has fixed rate of 300. and count may be 3. then it is like 300*3. all those product totals must be added to the TOTAL div. but here everything is fine but the TOTAL is a minus figure which is wrong. in this image if monthly rate is 300. then the TOTAL should be (14*300)+(5*300) = 5700.
do u have any idea i can do this another way. or any fix for this.

0

OK, so far I would look your code... In your 2nd portion line 136, you are calling a function with Ajax. The problem is that you are expecting it to return the value read from the database, but the data may comes back after your javascript function has advanced and finished the function call. The reason is Ajax is asynchronous, so the function will NOT wait for the return value but keeps going (and compute totalprice). If you want to compute it, you must use 'onreadystate' (in your case it is in :success) inside the Ajax object to compute and display it. However, your remove does not need to wait for the database, so you can just do it in your normal function call.

One more comment on your code in the 2nd portion line 124-135, you should use 'else if' instead of 'if'. If you use 'if' 3 times, the function will evaluate all 3 if-statements. But in your case, the value assigned to unit_price is mutual exclusive. As a result, you do not need to evaluate other cases once you found out what unit_price is. You should change it to...

if(count <= 10) {
  unit_price = 10;
}
else if(count <= 20) {  // already know that the count is >10 from previous condition check
  unit_price = 20;
}
else if(count <= 30) {  // already know that the count is >20 from previous condition check
  unit_price = 30;
}
else {  // if count>30, what would you do?
  unit_price = 100;
}

Edited by Taywin: n/a

0

OK, so far I would look your code... In your 2nd portion line 136, you are calling a function with Ajax. The problem is that you are expecting it to return the value read from the database, but the data may comes back after your javascript function has advanced and finished the function call. The reason is Ajax is asynchronous, so the function will NOT wait for the return value but keeps going (and compute totalprice). If you want to compute it, you must use 'onreadystate' (in your case it is in :success) inside the Ajax object to compute and display it. However, your remove does not need to wait for the database, so you can just do it in your normal function call.

One more comment on your code in the 2nd portion line 124-135, you should use 'else if' instead of 'if'. If you use 'if' 3 times, the function will evaluate all 3 if-statements. But in your case, the value assigned to unit_price is mutual exclusive. As a result, you do not need to evaluate other cases once you found out what unit_price is. You should change it to...

if(count <= 10) {
  unit_price = 10;
}
else if(count <= 20) {  // already know that the count is >10 from previous condition check
  unit_price = 20;
}
else if(count <= 30) {  // already know that the count is >20 from previous condition check
  unit_price = 30;
}
else {  // if count>30, what would you do?
  unit_price = 100;
}

Thanks for the IF condition part. have fixed that one. But for the ajax calling function i have made async:false. means it will wait for the data. and once the data receives only the other potions will execute. i used alert functions there to check, and the data is retrieving as i expected. my problem is calculating and updating the TOTAL div. the last function.

0

OK... Your code in line 139 may be wrong...

totalprice+=count-(purchased[i].cnt)*actual_rate;

shouldn't it be...

totalprice += (count-purchased[i].cnt)*actual_rate;

instead?

0

OK, then I need to try to narrow the bug down using alert function... Please do as followed and tell me the results:

replace line 139 with these lines of code

//from
  totalprice += (count-purchased[i].cnt)*actual_rate;

//to
  alert("Before: "+i+"\n"+count+"\n"+purchases[i].cnt+"\n"+actual_rate);
  totalprice += (count-purchased[i].cnt)*actual_rate;
  alert("After: "+i+"\n"+count+"\n"+purchases[i].cnt+"\n"+actual_rate);

By the way, you are sure that count is always correct, right?

replace line 109 with these lines of code

//from
  totalprice-=purchased[i].price*purchased[i].cnt;// recalculate the price
  purchased[i].cnt = 0;
//to
  alert("Before: "+i+"\n"+purchased[i].price+"\n"+purchases[i].cnt);
  totalprice-=purchased[i].price*purchased[i].cnt;// recalculate the price
  purchased[i].cnt = 0;
  alert("After: "+i+"\n"+purchased[i].price+"\n"+purchases[i].cnt);

replace line 87 with these lines of code

//from
  totalprice+=msg.price;
//to
  alert("Before: "+msg.price+"\n"+totalprice);
  totalprice+=msg.price;
  alert("After: "+msg.price+"\n"+totalprice);

Oh, I forgot to mention one thing. When you do debugging and you describe what happen, it means that you are supposed to explain how it happens step by step not in summary. It is similar to the way you report a bug. ;)

For example, I asked you earlier about how to reproduce this display bug, I was looking for something like as followed:
1.Open the page, the total is still 0
2.Add an item using drag & drop, the total is now -3456. The added item price is xxx and the count is xx, so the expected value of total should be xxxx.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.