Reputation: 705
I'm grabbing some information out of a database and passing it to some JavaScript using json_encode()
. The line: var row_data = <?php echo $month_stats ?>;
is dumping the object into the JS.
But now I want to abstract my JS into an external file, so suddenly I can't just echo
the contents of the object into the JS since PHP won't have any presence there.
So I need to somehow (via AJAX?) send the PHP object $month_stats
directly to the JS so that it can use the information independently of PHP, but I'm not sure how this is implemented. Any pointers?
<?php
include 'db.php';
$month_stats = generate_monthly_count_stats($conn);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var row_data = <?php echo $month_stats ?>;
console.log(row_data);
</script>
</head>
<body>
</body>
</html>
Upvotes: 0
Views: 243
Reputation: 3235
If you reference the variable row_data
in your included Javascript file, it should work, as you are declaring that in the global scope. Here's one article for reference: http://snook.ca/archives/javascript/global_variable
Upvotes: 0
Reputation: 1812
When you put the JS into an external file, make it a function with one parameter.
In your .js file:
function logRowData(var1)
{
console.log(var1);
}
In your .php file:
<head>
<?php
include(filename.js);
?>
</head>
To log the stats, you can call in the php file.
<script type="text/javascript">
logRowData($month_stats)
</script>
Upvotes: 1
Reputation: 1479
You can create some javascripn function in .js file
myFunction(obj) {
console.log(obj);
}
in your php file you can do that:
<script type="text/javascript">
myFunction(<?php echo $month_stats ?>);
</script>
Upvotes: 1
Reputation: 785
You can simply echo the variable and access it in an external file:
<script type="text/javascript">var row_data = <?php echo $month_stats ?>;</script>
<script type="text/javascript" src="external.js"></script>
row_data is now a global variable, so you can access it in the external.js. However it is better to add it to a namespace if you have lots of other variables..
Upvotes: 1