Below is a small snippet from a code I saw with jquery and PHP.
Notice the PHP part on line 5, I generally put my javascript into separate files so how would I be able to keep my JS in separate files but still use PHP when needed like below?
//when the DOM is ready
$(document).ready(function(){
//settings on top
var domain = 'http://davidwalsh.name/';
var initialPosts = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
//function that creates posts
var postHandler = function(postsJSON) {
$.each(postsJSON,function(i,post) {
What I generally do is :
For instance, I would have something like this, I suppose :
my-file.php :
So, in PHP, we declare tha variable and set its value. This is the “dynamic” part.
and, in my-file.js :
Here, in the static JS file, we only use the value ; nothing here is dynamic, and this file can be cached by the client — to not be re-downloaded on each page.
The problem with that idea is the JS file depends on some initialisation done in the PHP file 🙁
So, it might be a good idea to have a “default value” in the JS file, just in case…
Also, you have to have a good namming convention, to not have several files using/declaring/depending on the same JS variable ; it might be a good idea, actually, to put all your “configuration variables” inside a single javascript object, to not pollute the global namespace…