L
L
littox2014-03-19 16:56:33
PHP
littox, 2014-03-19 16:56:33

How to pass variable value from php script to javascript?

Good day!
Tell me, is there a way to pass the value of a variable between php and js scripts if they are in separate files? For example, there is test.php in it $a="hello world!";
How to get value of $a variable from php in script.js?

alert(" переменная из test.php ");  //сюда нужно подставить хелло ворлд из пхп

If everything is in one file, then it’s clear, you can do it simply, for example, alert("<?=$a?>");what if js is separated?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
N
nowm, 2014-03-19
@nowm

First way: A separate AJAX request to a PHP file that will return something like JSON data, which will then be available from JS.

<?php
$a = 'text for js_variable';
?>
<!DOCTYPE html>
<html>
  <head>
    <script>
      //Определяется переменная, которая будет доступна для 
      // всех JavaScript, подключаемых на данной странице
      var js_variable = '<?php echo $a; ?>';
    </script>
    <!-- 
      В файле /scripts/myscript.js происходит обращение 
      к переменной js_variable 
    -->
    <script src="/scripts/myscript.js"></script>
  </head>
  <body>blah-blah-blah</body>
</html>

// Выскочит алерт с текстом «text for js_variable».
alert(js_variable);

Here. In the HEAD part of the HTML page, you define a variable that will be available to the rest of the JS code. The main thing is that you need to define it before the scripts that will use it are connected.
The third way: If your web server is Apache, then you can add the following lines to .htaccess in the root of the site:
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js

<FilesMatch "\.js$">
SetHandler application/x-httpd-php
</FilesMatch>

Then you can execute PHP code directly in JS files. But it will be executed only in those JS files that are in the folder with the site. If scripts are loaded from third-party resources, the PHP code will not work there.

F
freddy, 2014-03-19
@mfred

<? $a="hello world!";?>
<script>var a = <?=$a?>;</script>

it is natural to set this before connecting the script, and in js already usealert(a);

1
1001001 111, 2014-03-19
@IgorO2

Use cookies or sessions

4
4ikist, 2014-03-19
@4ikist

variable: var param = '<?=$param;?>';
array:var object = <?=json_encode($array);?>;

A
Alexander Khirenko, 2014-03-19
@Satanpit

You can write PHP parsing in JS files in .htaccess

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question