How to use a PHP variable in javascript?


Can you declare a variable in PHP and then use it in JavaScript?


    var w_qtd_v = 0;

<script language="javascript">
    w_qtd_v = w_qtd_v + 1;
asked by anonymous 12.08.2014 / 16:41

3 answers


The javascript has no way to update the value of the PHP variable, only php manipulates / creates the JS. To do this update, you will need an ajax, just after you have changed the value of the variable with JS ... if that is the issue.

PHP runs server side to create the page, and JS runs on the client side with the page already created. The only way they "talk" is via ajax.

If you are using a framework, such as zend and etc, you usually use a template engine to work with variables in HTML, you can also pass these variables to JS, example of using variables with the template engine RainTpl


// include
require "library/Rain/autoload.php";
// namespace
use Rain\Tpl;

$config = array(
    "tpl_dir"   => "vendor/rain/raintpl/templates/test/",
    "cache_dir" => "vendor/rain/raintpl/cache/"

Tpl::configure( $config );

$t = new Tpl;



<script language="javascript">
    var title = "{$title}";

or simply do so


$title = "Hello";

<script language="javascript">
    var title = "<?php print $title; ?>";
12.08.2014 / 16:54

Try this:

$variavel = "texto";

  var variavel = "<?php echo $variavel; ?>";
12.08.2014 / 16:50

PHP and Apache are responsible for interpreting the php page and sending it back to the client, the user's browser, the html code and in this process php can send javascript code inside the html according to the processing. >

However, depending on the case, this can be done through an AJAX request where JS will send a request to the server and obtain a response, asynchronously, without interrupting its application. So, with that answer in JS, you can do whatever you want.


13.08.2014 / 15:25