I have a few lines of jQuery in my web application. This code is inline at the moment because it accepts a couple of PHP variables.
<script type="text/javascript">
$(document).ready(function(){
$('.post<?php echo $post->id; ?>').click(function() {
$.ajax({
type: 'POST',
url: 'http://domain.com/ajax/add_love',
data: {
post_id: <?php echo $post->id; ?>,
user_id: <?php echo $active_user->id; ?>,
<?php echo $token; ?>: '<?php echo $hash; ?>'
},
dataType: 'json',
success: function(response) {
$('.post<?php echo $post->id; ?>').html(response.total_loves).toggleClass('loved');
}
});
return false;
});
});
</script>
I’m a big fan of best practices though, so I would like to move my jQuery into an external JS file.
How could I achieve such a feat?
Any tips? I’m still relatively new to jQuery and PHP.
Thanks!
🙂
My solution combines several techniques, some of which are already mentioned within the answers to this question.
Yes, separate PHP from JS
First of all: yes, you should separate your JS from PHP. You can put it in a separate file, but you will need to make some changes into your current code. Do not make JS file dynamically generated – it actually kills the advantages of separating JS code into separate file (you cannot cache it etc.).
Common variables as global variables / function arguments
Next, store your common variables as global variables in the header of HTML file (you do not really have much choice, although there are other alternatives), preferably grouped in one object:
Alternatively you can pass all of them as argument(s) to the function you will call, but I assumed you are using them also in other places in your script.
Container-dependent data stored in
data-attributesThen use
data-attributes for storing real data associated with containers. You won’t needpost1/post2/post3-like classes and separate event handlers for them:instead of eg.:
How to read globals and
data-attributes from external JS fileAnd then your JavaScript may look like:
And this should be sufficient (although I did not test it).