+ 5
How to save the value of a variable from php to js?
How to save the value of a variable from php to js?
12 RĂ©ponses
+ 13
U work with a.php and do:
<?php
$a = 5;
?>
<script>
var a = <?php echo $a; ?>;
alert(a)
</script>
just copy this code to php code playground and you will see, how this is powerful
+ 4
Boby sure, we just need to make sure that they are properly encoded (like single/double quotes etc.)
+ 3
Good question! I do that by HTTP request. I send the value of the variable as a response text and my JavaScript function then process it into variable.
+ 3
Boby : var a = '<?php... then, you are missing ' and before ;
+ 2
Jan Ć tÄch Could you please explain how you do this?
de do does this really assign the value of PHP "a" to the JS variable? Does it also work with numbers, etc.?
+ 2
There are two different cases.
1) You are loading or reloading the webpage
2) You want to change the value of the variable without reloading the webpage (AJAX will be used).
In the first case, you can just do that as @de do said. Just add PHP tags into your script tags in your HTML file and place echo statement with the value into it.
Example:
index.php:
<html>
<head>
<title>Test</title>
<script>
var x = <?php echo 73; ?>
<script>
<head>
<body>
Hello world
</body>
<html>
In the second case, you need to know AJAX (Asynchronous Javascript And Xml). You send an XML HTTP request to the server and when you get the response, you execute another Javascript function that will take the response text as an argument and assign it to the variable. Here is how can you do that:
index.html:
<html>
<head>
<title>Test</title>
<script src="script.js" />
<head>
<body>
<button onclick="getVar()">Get variable</button>
</body>
<html>
script.js:
function getVar()
{
var req = false
req = new XMLHttpRequest();
if (!req) {console.log("Your browser doesn't support AJAX.");}
req.onreadystatechange = function()
{
if(req.readyState == 4)
{
responseFunc(req.responseText, subject);
}
}
req.open("GET", "ajax.php", true);
req.send(null);
}
function responseFunc(response)
{
var x = response;
}
ajax.php:
echo 73;
After the user clicks on the button, the JavaScript variable x will contain value 73 sent from php script running on the server.
+ 2
Jan Ć tÄch thanks. But I still don't get the AJAX part.
Do you know any good online tutorial about AJAX? Or a good book?
+ 2
Not really, I learnt from more sources and don't know it completely. I just copy and paste a function creating the request and call it with different parameters whenever I want. But I would recommend you learning on w3schools. You should start on this webpage: https://www.w3schools.com/xml/ajax_intro.asp.
+ 2
try this one:
<?
$text="Example PHP Variable Message";
echo '<script>alert("'.$text.'")</script>';
+ 1
de do , can we alert string same way ?
+ 1
trying to do like so i get nothing
<?php
$a = "hello";
?>
<script>
var a = <?php echo $a; ?>;
alert(a)
</script>
+ 1
De do, excellent , thanks !