How to embed PHP into Javascript?

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
chxxangie
Forum Newbie
Posts: 12
Joined: Wed Sep 19, 2007 10:00 pm

How to embed PHP into Javascript?

Post by chxxangie »

is it possible?

Code: Select all

<SCRIPT LANGUAGE="Javascript">	
      document.location = "product.php?search=<?php echo $search;?>"
   </SCRIPT>
User avatar
Josh1billion
Forum Contributor
Posts: 316
Joined: Tue Sep 11, 2007 3:25 pm

Post by Josh1billion »

Nope, Javascript is client-side and PHP is server-side. You might be able to make PHP script calls with Ajax but I'm not sure as I've never used Ajax.

Looking at your example code, I'm not entirely sure what you're trying to do, but if you had all that within a print function around all that, you could output PHP variables into your Javascript script if that's what you're asking about.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

sure you can do that - give it a try!
sunilbhatia79
Forum Newbie
Posts: 24
Joined: Sun Nov 11, 2007 9:37 pm
Location: Mumbai, India

Post by sunilbhatia79 »

You can do it... ultimately you are just echoing the $search variable to the HTML output... Instead of using <?php echo $search;?> you could also use <?=$search?>. This is much better for maintenance and debugging.

Try this:

Code: Select all

<SCRIPT LANGUAGE="Javascript">   
      document.location = "product.php?search=<?=$search;?>"
   </SCRIPT>
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

careful about using short tags, they'll be turned off by default soon.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

sunilbhatia79 wrote:You can do it... ultimately you are just echoing the $search variable to the HTML output... Instead of using <?php echo $search;?> you could also use <?=$search?>. This is much better for maintenance and debugging.
Care to explain why? I've always found that using shortcuts in code makes them harder to maintain and debug.
Post Reply