So many times on this site I see people trying to do things like this : <script
ID: 650591 • Letter: S
Question
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?
Explanation / Answer
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.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.