3

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?

7
  • 2
    Best solution would probably be AJAX. Mixing PHP and JS like that is never a good idea. Commented Dec 5, 2012 at 23:30
  • Can you explain in detail? Use Ajax to load javascript? Commented Dec 5, 2012 at 23:32
  • Using AJAX to load required variables. Commented Dec 5, 2012 at 23:33
  • 1
    You can use a global JavaScript variable that you can dump into your html and still can use your script the way you just mentioned. <script> GlobalData = { <? json_encode($items) ; ?> }; </script> and then in you javascript you will be using GlobalData object. Commented Dec 5, 2012 at 23:38
  • 2
    @elclanrs AJAX doesn't work well if the variable needs to be used directly in the page. Commented Dec 5, 2012 at 23:43

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

I don't see how AJAX is a bad solution... It works just fine jsbin.com/ohosuf/1/edit
@elclanrs I'm not saying it's bad, but if your server side application already has the data when the page is rendered I don't see why AJAX should even be used but for the fewest of occasions.
0

set a header for javascript (application/javascript) in a php file. then in the script tag, point the src attribute to that file. Do whatever echoing (or conditionals, retrieving) is needed in that respective php file.

Comments