How to use a PHP variable in javascript?

4

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

Example:

<?
    var w_qtd_v = 0;
?>

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

3 answers

5

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

index.php

// 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;
$t->assign('title','Hello!');
$t->draw('test');

test.html

<html>
...
<p>
{$title}
</p>
</html>

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

or simply do so

<?php

$title = "Hello";

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

Try this:

<?php
$variavel = "texto";
?>


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

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.

References:

13.08.2014 / 15:25