Incorporating small Javascript function into my PHP shopping cart

Hey, I have created a small Javascript function which automatically calculates the postage of an order using a small javascript function. I am now trying to include it in my shopping cart and having some problems. The Javascript works by replacing whatever is in the contents of a <div id=“regiondiv”> with the necessary value from my database.

At the moment, the last lines of my shopping cart look as such:

		$output[] = '<h3 align="right">Postage: &pound;<div id="regiondiv">0.00</div></h3>';
		$output[] = '<h2 align="right">Total: &pound;'.$total.'</h2>';

When I choose a value in a drop-down box the value in the ‘regiondiv’ div changes to the correct postage. I can’t seem to work out how to have this also affect the $total as well though. I’ve tried some basic things like:

			$postage = '<div id="regiondiv">0.00</div>';
			$total += ($Price + $postage);

But had no success with this. Does anyone know how I could add the value from this <div> tag to my final total???

Hi slaterino,

It seems you’re trying to merge PHP (server-side) with Javascript (client side) which isn’t possible while the page is loading.

You need to explore the idea of AJAX if you want a client side action (ie selecting a dropdown option) to modify the page by processing a server side script).

Alternatively, read the values from the database into a javascript array so that they are accessible from the client browser.

Of course you also need to consider what happens if the user has javascript disabled … do they get free postage?? :wink:

I hope that helps.



It’s just I really have no idea what is the best way to go about this. I will have a look into using AJAX and see if I can work out exactly what is going on!!!


Why don’t you calculate postage in PHP?

I think I could calculate the postage in PHP, although I just really want the postage to be worked out automatically, so that the user just chooses from a drop-down box and the postage is worked out accordingly. Is there a way this could be done using just PHP? As this would be the perfect solution!


Well, if you want the postage to be worked out automatically, it must be done using javascript. No AJAX needed.
But your code, $total += ($Price + $postage); doesn’t look as javascript to me.