views:

385

answers:

6

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) {
+5  A: 

What I generally do is :

  • put as much JS as possible in a .js file (for caching on the client-side and all that)
  • this JS code uses a JS variable
  • that JS variable is declared / initialized from a PHP file ; this is the only part where you need some code executed on the server-side, actually

For instance, I would have something like this, I suppose :

my-file.php :

var thisIsMyJSVar = '<?php echo $test; ?>';

So, in PHP, we declare tha variable and set its value. This is the "dynamic" part.

and, in my-file.js :

//when the DOM is ready  
$(document).ready(function(){  
    //settings on top  
    var domain = 'http://davidwalsh.name/';  
    var initialPosts = thisIsMyJSVar;  // Use the JS variable declared in the PHP file
    //function that creates posts  
    var postHandler = function(postsJSON) {  
        $.each(postsJSON,function(i,post) {

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...

Pascal MARTIN
great thats what I was thinking, does it make a differene if the php sets the JS var before or after the JS file is included?
jasondavis
In this case, the JS code will be executed when the page is fully loaded (because of the $(document).ready) ; so it should change much ;; but, in other cases, the JS code could need the variable right when it's loaded ;; so, as a precuation, I think it would be better to always declare+initialize the variable before including the JS script.
Pascal MARTIN
ok thanks, I think yahoo recommends including your >JS file at the end of your page anyways
jasondavis
As the download/loading of JS files is blocking (in some browsers, anyway -- not sure about the most recent ones), yes, it can be better for the loading speed of the page ;; at least, if your page doesn't need this JS script before the end of it's loading (here, it doesn't, as the JS code is executed only when the page is fully loaded)
Pascal MARTIN
+2  A: 

If you want to keep your Javascript separate from your PHP, then use a PHP file to generate a small chunk of Javascript just to set variables. Then use those variables from your .js file:

HTML:

<script>
var INITIAL_POSTS = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
</script>
<script src="my.js">

my.js Javascript file:

//when the DOM is ready  
$(document).ready(function(){  
    //settings on top  
    var domain = 'http://davidwalsh.name/';  
    var initialPosts = INITIAL_POSTS;  
    //function that creates posts  
    var postHandler = function(postsJSON) {  
        $.each(postsJSON,function(i,post) {
Ned Batchelder
A: 

Hi This should work, i mean is the file .php? As the JS is client side, the php should be processed through the php engine BEFORE the browser processes the client side javascript?

tarnfeld
A: 

There are two basic ways to handle that that don't require mixing JavaScript and PHP at all:

  1. When PHP is generating the page, have it write that output (get_posts(0,$_SESSION['posts_start']); into a hidden input on the form (or elsewhere on the page). JavaScript can then access this readily
  2. Let JavaScript fetch that output from a separate PHP request via AJAX.

Generally, if it's the sort of value that won't change while the visitor is browsing the page (or you don't care if it changes, since you won't be updating other content dynamically), write it directly onto the page.

JavaScript and jQuery can then fetch that value easily with code like

var initialPosts = $("#that-hidden-field-mentioned-earlier").val();
VoteyDisciple
+1  A: 

You can always have the php "write" the javascript file instead of having it be static- there's nothing to stop <script src="script.php">...

David
If you do this, make sure you call `header("Content-Type: text/javascript")`
Macha
then it couldn't cache the file though..
jasondavis
How couldn't it? It sees a JS file (albeit with a weird extension).
Macha
It will cache just fine- you might have to tweak the headers a bit to get it to do it though.But you wouldn't neccessarily want it cacheing anyway since your writing the data in the file- if the page is cached, your data could be out of date.
David
A: 

Until someone drops in a cleaner answer:

You can define a global js variable in your php/html file, and refer to it in your script:

php/html:

<script>
var global = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
</script>

js:

...
var initialPosts = global;
...
Zed