Page 1 of 1

php with js will it work

Posted: Fri Nov 10, 2006 5:13 am
by itsmani1
Have look at this code: will it work?

Code: Select all

<table>
<tr>
<td class="header"><a href="#" onClick="buy('15413497'); return false;">
<img src="http://www.ticketchest.com/images/c_buy.jpg" border="0" height="18" width="95"></a></td>
</tr></table>

Code: Select all

<script>
function buy(id)
{
	var t = document.getElementById(id).value;
	alert();
	<?PHP
		$cartObj = new ShoppingCart;
		if(isset($_SESSION['cartItems']))
		{
			$cartObj -> $items = $_SESSION['cartItems'];
			$cart->add_items("Apples", 5);
		}
		else
		{
			$cartObj -> $items = NULL;
			$_SESSION['cartItems'] = $cartObj -> $items;
			$cart->add_items("Peach", 5);
			$_SESSION['cartItems'] = $cartObj -> $items;
		}
	?>
}
</script>

Posted: Fri Nov 10, 2006 5:43 am
by volka
No, php runs server-side, javascript client-side.
Usually there's no connection between them but a http request, i.e. some text that is transfered forth and back.
When javascript is executed php is (long) gone.

Posted: Fri Nov 10, 2006 5:49 am
by itsmani1
then what could be the best way to do this?

thanks

Posted: Fri Nov 10, 2006 5:52 am
by volka
Send the necessary parameters with a http request to the server, e.g.

Code: Select all

<form method="post" action="additem.php">
	<div>
		<input type="hidden" name="itemid" value="15413497" />
		<input type="submit" value="add to cart" />
	</div>
</form>

Posted: Fri Nov 10, 2006 6:41 am
by Z3RO21
I am not too key on AJAX but couldn't this be a use of it?

Posted: Fri Nov 10, 2006 6:58 am
by volka
You can replace all "normal" http request by ajax if you like ;)

Posted: Fri Nov 10, 2006 12:49 pm
by John Cartwright
I wouldn't restrict your users to having javascript enabled, especially for something like a shopping cart.

Posted: Fri Nov 10, 2006 12:56 pm
by RobertGonzalez
Seriously, just put the data into a hidden form field and post the form back to the page.