Embedding PHP variables in Javascript


Is this actually possible? I’m using AJAX and I’d like for my get function to send a JSON object that has its field values taken from the values of PHP variables defined elsewhere on the page.

Much thanks,


Yeah it is possible. If its in the html area you can traverse the DOM to get the data. Else you can define the values in a script block in the head section.

This is a little tricky to explain… the answer is yes but not in the sense of “javascript reading PHP variables”.

User requests your webpage by clicking a link or typing its URL.

PHP code is executed, which produces HTML output that the web server passes back to the browser as the response.

Now you have a webpage, which may contain some JavaScript the browser is executing locally.

There are no PHP variables anymore at this point. It’s just HTML in a browser window. That PHP produced the page isn’t known to the browser or to the JavaScript, and it can’t talk to the PHP code that produced the page.

But your PHP code could have output some JavaScript as part of its response… you can

<script type="text/javascript">
var myvariable = <?php echo $myphpvariable; ?>;

to get something like

<script type="text/javascript">
var myvariable = 3;

in the HTML sent to the browser, making that PHP variable’s value available to JavaScript.

You can also have your JavaScript code using AJAX to make request to a PHP script that outputs variables in its response, making them available to the JavaScript in the AJAX response…

Thanks a lot guys.

Dan, what you’ve described is basically what I managed to do. So, I’m happy to see that I had the right idea about what is and isn’t possible.