Why do you need to echo the PHP variable before passing it into javascript?
For example,
drawChart(600/50, <?php echo $day; ?>, ...)
Why would I need the part? Why not just do
drawChart(600/50, $day, ...)
?
Thank you
Why do you need to echo the PHP variable before passing it into javascript?
For example,
drawChart(600/50, <?php echo $day; ?>, ...)
Why would I need the part? Why not just do
drawChart(600/50, $day, ...)
?
Thank you
The question you are asking requires to explain a strong conceptual issue. The PHP code is processed on a webserver, and is called server-side code, while the javascript code is executed on the web browser AFTER the server has returned the page's html and is called client-side code. So, you have different stages of execution on different platforms. The javascript code is not capable of evaluating the PHP source code, and has no knowledge of the PHP variables and their state.
The code in your question represents a javascript function call and one of the parameters happens to be a PHP variable. The PHP variable has to be evaluated on the server before the browser receives it, so the javascript call will work correctly. If the $day
variable has the value 13
(for the example' sake), the following code:
drawChart(600/50,
<?php echo $day; ?>
, ...)
will be rendered into the HTML like this:
drawChart(600/50,
13
, ...)
But, if you skip the PHP stuff, you'll get:
drawChart(600/50,
$day
, ...)
which will probably not work in the browser.
Also, you may have a javascript variable with the name $day
, so the code will use it, instead of the PHP evaluated one, and could even work without errors, but with unexpected behavior.
Update: A much better explanation for this is available in a response to an older question.
What is the difference between client-side and server-side programming?
This confuses a lot of web developers early on.
Your PHP code is running server-side. The variable $day
is evaluated at the time a web request reaches your server.
Your JavaScript code runs client-side. From your server's perspective, it is a bunch of static text sent down to the user's browser. The browser then interprets this static text as code and executes it.
You can't "share" variables between PHP and JavaScript because by the time the JavaScript is executed, you are no longer in a context where a server is running PHP.
So you use echo
to output the value of $day
while it is a variable in a PHP context; its value then gets injected into JavaScript where it is no longer a variable from the client's context. (Rather, in your example it will be as if you called drawChart
with hard-coded values.)