Answer the question
In order to leave comments, you need to log in
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 "); //сюда нужно подставить хелло ворлд из пхп
alert("<?=$a?>");
what if js is separated?
Answer the question
In order to leave comments, you need to log in
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);
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch "\.js$">
SetHandler application/x-httpd-php
</FilesMatch>
<? $a="hello world!";?>
<script>var a = <?=$a?>;</script>
alert(a);
variable: var param = '<?=$param;?>';
array:var object = <?=json_encode($array);?>;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question