javascript - Including PHP variables in an external JS file? -
i have few lines of jquery in web application. code inline @ moment because accepts 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 big fan of best practices though, move jquery external js file.
how achieve such feat?
any tips? i'm still relatively new jquery , php.
thanks!
:)
my solution combines several techniques, of mentioned within answers question.
yes, separate php js
first of all: yes, should separate js php. can put in separate file, need make changes current code. not make js file dynamically generated - kills advantages of separating js code separate file (you cannot cache etc.).
common variables global variables / function arguments
next, store common variables global variables in header of html file (you not have choice, although there other alternatives), preferably grouped in 1 object:
var globals = <?php echo json_encode(array( 'active_user_id' => $active_user->id, 'token' => $token, 'hash' => $hash, )); ?>;
alternatively can pass of them argument(s) function call, assumed using them in other places in script.
container-dependent data stored in data-
attributes
then use data-
attributes storing real data associated containers. won't need post1
/post2
/post3
-like classes , separate event handlers them:
<div data-post-id="10">here something</div>
instead of eg.:
<div class="post10">here something</div>
how read globals , data-
attributes external js file
and javascript may like:
$(document).ready(function(){ $('[data-post-id]').click(function() { var el = $(this); var data = { 'post_id': el.data('post-id'), 'user_id': globals.active_user_id }; data[globals.token] = globals.hash; $.ajax({ 'type': 'post', 'url': 'http://domain.com/ajax/add_love', 'data': data, 'datatype': 'json', 'success': function(response) { el.html(response.total_loves).toggleclass('loved'); } }); return false; }); });
and should sufficient (although did not test it).
Comments
Post a Comment