Possible Duplicate:
How can I separate javascript from PHP when the JS needs a PHP variable?
How to define a variable in JavaScript with PHP echo function?
For example I have the following Javascript code. It uses PHP variables.
<script>
$(function() {
for(var items = 1; items <=<?php echo $items;?>; items++){
print_percentage_is("div.is"+items);
}
});
</script>
What's the best solution to separate the Javascript code with my Html/PHP code? For this case I can not use this way
<script type="text/javascript" language="javascript" src="/js/change.js"></script>
Do I need to create a PHP file and put the javascript in? What's the best solution?
If data needs to be directly available to your JavaScript, AJAX is a pretty horrendous solution. Instead, you can create a separate <script> tag to pass the PHP variables over to the page, using json_encode().
This is an example:
<script type="text/javascript">
var my_variable = <?php echo json_encode($my_variable); ?>;
</script>
In the page you would then use it like so:
<script>
$(function() {
console.log(my_variable);
});
</script>
If you need to pass multiple variables, it's sometimes better to group them together in PHP like this:
<?php
$data = array(
'items' => array(1,2,3,4),
'users' => array(array('name' => 'John'), array('name' => 'Jane')),
);
?>
<script>
var data = <?php echo json_encode($data); ?>;
</script>
<script>
$(function() {
console.log(data.items);
console.log(data.users);
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With