php with js will it work

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
itsmani1
Forum Regular
Posts: 791
Joined: Mon Sep 29, 2003 2:26 am
Location: Islamabad Pakistan
Contact:

php with js will it work

Post 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>
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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.
User avatar
itsmani1
Forum Regular
Posts: 791
Joined: Mon Sep 29, 2003 2:26 am
Location: Islamabad Pakistan
Contact:

Post by itsmani1 »

then what could be the best way to do this?

thanks
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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>
Z3RO21
Forum Contributor
Posts: 130
Joined: Thu Aug 17, 2006 8:59 am

Post by Z3RO21 »

I am not too key on AJAX but couldn't this be a use of it?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

You can replace all "normal" http request by ajax if you like ;)
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

I wouldn't restrict your users to having javascript enabled, especially for something like a shopping cart.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Seriously, just put the data into a hidden form field and post the form back to the page.
Post Reply