So many times on this site I see people trying to do things like this :

<script type="text/javascript">
  $(document).ready(function(){

     $('<?php echo $divID ?>').click(funtion(){
       alert('do something');
     });

  });
</script>


I don't think that this is some sort of pattern that people naturally fall into. There must be some sort of tutorial or learning material out there that is showing this, otherwise we wouldn't see it so much. What I'm asking is, am I making too big a deal of this or is this a really bad practice?

EDIT :
Was speaking to a friend of mine about this who often puts ruby in his JavaScript and he brought up this point.

Is it ok to dynamically place application wide constants in your JavaScript so you don't have to edit two files. for example...

MYAPP.constants = <php echo json_encode($constants) ?>;


also is it OK to directly encode data you plan to use in a library

ChartLibrary.datapoints = <php echo json_encode($chartData) ?>;   


or should we make an AJAX call every time?

Typically, it is bad practice to use language X to generate code in language Y.

Try decoupling the two languages by making data their only interface -- don't mingle the code.

In your example, you could improve the code by using PHP to populate a cfg structure that's available to JavaScript:

<script type="text/javascript">
  var cfg = {
    theId: "<?php echo $divID ?>",
    ...
  };

  $(document).ready(function(){
     $("#" + cfg.theId).click(funtion(){
       alert('do something');
     });
  });
</script>


This way, PHP only cares about populating the data structure and JavaScript only cares about consuming the data structure.

This decoupling also leads the way to loading the data asynchronously (JSON) in the future.

Update:

To answer the additional questions you asked with your update, yes, it would be good practice to apply the DRY principle and let PHP and JavaScript share the same configuration object:

<script type="text/javascript">
  var cfg = <?php echo json_encode($cfg) ?>;

  ...


There is no harm in inserting the JSON representation of your configuration directly into your page like this. You don't necessarily have to fetch it via XHR.
