How can I access PHP variables from Javascript where the PHP code exists in a separate file?
The code I have is:
<?php
$res = "OK";
?>
<html>
<head>
<script type="text/javascript">
function myFunc()
{
res = <?php echo json_encode($res); ?>;
console.log("res = " + res);
}
</script>
</head>
<body>
<button onclick="myFunc()">Click</button>
</body>
</html>
Now, if I were to move my php code to a separate file called a.php, how can I access $res? Assume I am calling a.php with a GET request (XMLHttpRequest object).
Try-
res = "<?php echo json_encode($res); ?>";
Related
I have this below code in a file named test.php, whose task is to create a JSON object and transfer it to a function in JS.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if($row) {
$obj->txndate = $row['date'];
$obj->txnid = $row['txnid'];
$obj->atomid = $row['atomid'];
$obj->amount = $row['amount'];
$myJSON = json_encode($obj);
$encodedJSON = json_encode($myJSON); //final variable in PHP to pass to below function.
//JS begins here
echo <<<JS001
<script type="text/javascript">
var msg = {$encodedJSON};
var ThunkableWebviewerExtension = {
postMessage: function (message) {
if (window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(message);
} else {
window.parent.postMessage(message, '*');'
}
}
};
ThunkableWebviewerExtension.postMessage(msg);
alert(msg);
</script>
JS001;
} else {
echo 'Incorrect ID';
}
?>
</body>
</html>
I have this piece of script, but I can only write it inside PHP - because the value the function requires, is stored in a PHP variable. All it should do is fetch the PHP's encodedJSON variable's value and store it in a local JS variable msg. Then, I created a function whose task is to POST a message, and called it next. All this worked perfectly when run in a separate HTML file, in which JS was written individually.
What should I do, to make the JS piece of code run inside PHP code? Thanks!
Given that $myjson contains the json string in php, then
var msg = {$myJSON};
to understand better above code is equivalent to:
var msg = JSON.parse('{$myJSON}')
is the way to convert it to js object from php variable.
Please see comments in the code for further help.
Please run below code and see how console.log is printing the json object:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
//started with hard coded data to show a working copy paste example
$row = array('date'=>'09-Oct-2020','txnid'=>1234,'atomid'=>456,'amount'=>21345);
if($row) {
$obj = new stdclass(); //op should add this to avoid warning
$obj->txndate = $row['date'];
$obj->txnid = $row['txnid'];
$obj->atomid = $row['atomid'];
$obj->amount = $row['amount'];
$myJSON = json_encode($obj);
//to see the json encode value in php
//var_dump($myJSON);
//this is not needed in op code
//$encodedJSON = json_encode($myJSON); //final variable in PHP to pass to below function.
//JS begins here
echo <<<JS001
<script type="text/javascript">
//php json string is converted to js object here
var msg = {$myJSON};
//see msg object printed in console
console.log(msg);
</script>
JS001;
} else {
echo 'Incorrect ID';
}
?>
</body>
</html>
I have this simple script
<!DOCTYPE html>
<html>
<head>
<?php
$latitude = 53.071174;
$longitude = 28.296536;
?>
</head>
<body>
<script>
var jsLatitude = <?php echo json_encode($latitude); ?>;
var jsLongitude = <?php echo json_encode($longitude); ?>;
alert(jsLatitude);
alert(jsLongitude);
</script>
</body>
</html>
but it gives me a Syntax error at this line
var jsLatitude = <?php echo json_encode($latitude); ?>;
What am I doing wrong?
Ok, as suggested by #Markus Zeller and #Teemu it was just the extension of the file (I was working on an HTML file instead of a PHP) and I was working on my personal PC.
Changing the extension and uploading the script to a server with PHP installed solded the problem.
I'm having a problem trying to use a PHP variable within JavaScript. I keep getting the following message.
"Invalid or unexpected token. Message: Undefined variable: example."
I'm unsure why example is being undefined, as it is defined within the php code. Here is my code:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = "<?php echo json_encode($example); ?>";
</script>
Does anyone have any suggestions? I have also tried the following javascript that results in the same problem:
<script type="text/javascript">
var php_var = "<?php echo $example; ?>";
</script>
Firstly, your original code has a syntax error: $example = '2' needs a semicolon.
Secondly, the next piece of code is just assigning the string <?php echo $example; ?> to the JavaScript variable php_var where the $example PHP variable is first substituted. The $example variable should be initiated properly first, however, for this to work.
As a separate note: JS cannot execute PHP directly -- only a PHP server can do so. What you're most likely trying to do is this:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = '<?php echo $example ;?>';
</script>
This should work, use single quotes
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = '<?php echo $example; ?>';
</script>
Tried and working both variant:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = <?php echo json_encode($example); ?>;
console.log(php_var);
</script>
<script type="text/javascript">
var php_va = "<?php echo $example; ?>";
console.log(php_va);
</script>
I am currently trying to pass in PHP array to a javascript Function through onload();
In my SimilarDomains.php:
<?php
$domainsJS = json_encode($similarDomainsUnique);
?>
<body onload="init(<?php echo "\"$domainsJS\""; ?>);">
I do this to pass it as a string object in order to later process the string using JSON.parse(). In the javascript i have
var obj = JSON.parse(domainsJS);
for string processing. But it seems like I have a SyntaxError: syntax error # line 1. This is the HTML Doctype. If I remove the doctype, it just goes to the next first line. it only appears when I have the body onload calling php as I did.
How can I process this php array in order to be used in JavaScript. After all this is said and done, I then have to input the processed values into a JS array.
Here is what the body onload turns out to be in the HTML
<body onload="init("{"0":"estatelawyer.com","1":"reaestatelawyer.com","2":"estately.com","3":"thestate.com","4":"estaterescue.com","5":"boisestate.edu","10":"99acres.com","11":"1point3acres.com","14":"green-acres.com","22":"backcountry.com","24":"baby-kingdom.com","25":"landattorney.com","27":"siteground.com","28":"247realmedia.com","30":"siteground.biz","31":"arealme.com","32":"farming-simulator.com","33":"amkingdom.com","34":"searchengineland.com","35":"shoretelsky.com","36":"grantland.com","38":"amsoil.com","40":"lostrealm.ca","41":"kingdomofloathing.com","42":"shorewest.com","44":"domaintools.com","45":"domain.com.au","46":"realmadridstream.net","47":"farming2015mods.com","48":"travelandleisure.com","49":"landofnod.com","51":"bringmesports.com","52":"cricketcountry.com","53":"bringthebaconhome.com\/user\/dashboard","54":"ollando.com","55":"domain.com","57":"travelandlearntrips.com","58":"scarffruit.country","59":"78land.com","92":"propertylawyer.com","93":"propertylawyergroup.com","94":"propertyattorney.com","95":"rocketlawyer.com"}");">
You should just need to echo it straight up without any extra quotes because it's a JSON object
<body onload="init(<?php echo $domainsJS ?>);">
Add the json to a var in the JS
echo <<<EOT
<script type="text/javascript">//<![CDATA[
var jsn = " . json_encode($similarDomainsUnique);
var obj = JSON.parse(domainsJS);
//]]>
</script>
EOT;
This is poor coding:
<?php
$domainsJS = json_encode($similarDomainsUnique);
?>
<body onload="init(<?php echo "\"$domainsJS\""; ?>);">
There is no reason to be jumping back and forth from PHP mode to HTML mode.
There is PHP overhead to each time you change modes.
Below is the basic proper way to create an HTML page.
I like to get the HTML on its way to the Browser ASAP. That is why I flush the output buffer somewhere just after the <body> tag and the Browser will have a few things to do preparing for Start Render.
To accomplish your passing json to <javascript> I assign the value to $js then embed $js in the `
And PHP is never switched to HTML mode.
<?php ob_start("ob_gzhandler");
header('Content-Type: text/html; charset=utf-8');
header('Connection: Keep-Alive');
header('Keep-Alive: timeout=50, max=100');
header('Cache-Control: max-age=3600');
echo <<<EOT
<!DOCTYPE html>
<html lang="en">
<head><title>Sample</title>
<style>
body{font:400 1emArial,sans-serif;color: #f00 ;}
#page{width:100%;background:#ff0;border:solid .5em #000;padding:2em;}
#contents{max-width:50em;background:#00f;margin:0 auto 0;height:10em;color:#ff0;padding:1em;}
h1{color:#000;text-align:center;}
</style></head><body><div id="page">
EOT;
ob_flush();
$js = "\nvar jsn = '" . json_encode($similarDomainsUnique) . "';\n" ;
echo <<<EOT
<h1>Headline</h1>
<p>Paragraph</p>
</div></div></body>
</html>
<script type="text/javascript">//<![CDATA[
function init(){
$js
var obj = JSON.parse(jsn);
}
window.onload = init;
//]]>
</script>
EOT;
ob_end_flush();
?>
If you need obj to be use by other functions:
<script type="text/javascript">//<![CDATA[
var obj = '';
function init(){
$js
obj = JSON.parse(jsn);
}
window.onload = init;
//]]>
</script>
EOT;
ob_end_flush();
?>
I have a the code below in my js which obviously works if the js is in the php file
filter: '<?php echo $my_cat>'
how can i make a variable maybe in the php file and pull it in my external js file?
You have to place this below code at the top part of your test.php page
<script>
var filter = '<?php echo $my_cat>';
</script>
and simply you can check it on your external.js file by alert
alert(filter);
<?php
function showme(){
echo "HelloWorld";
}
?>
<script type="text/javascript">
var my_var = '<?php echo showme(); ?>' ;
</script>
You can also use short tags.
<script>
var filter = '<?=$my_cat?>';
</script>