Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to put PHP into my Javascript?

i am trying to use the following line of PHP in my JavaScript file, but can't get it to work:

var image = "<?php echo BASE_URL; ?>images/logo-marker.png";

The line below works fine but I would like to know why the above code won't work:

var image = "../images/logo-marker.png";

Thanks in advance.

4 Answers

You've got to do it the other way around. Put JavaScript inside your PHP.

It is. The JavaScript is already being added as a PHP include file, then the PHP within that JavaScript file (above) should run. Shouldn't it?

PHP is server side. It executes before the code is received by the client/browser. Javascript works client side. It is received from the server and executes in the browser.

As James suggested, you can have PHP generate and output Javascript (and HTML & CSS), but not the other way.

James/Shahriar, I did think that may be the case but was unsure due to it being added as a PHP include.

Thanks for clearing this up.