Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate PHP code and Javascript code [duplicate]

Tags:

javascript

php

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?


1 Answers

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>
like image 132
Ja͢ck Avatar answered Aug 18 '26 11:08

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!