Including PHP variables in an external JS file?
Asked Answered
C

6

4

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!

:)

Cassandry answered 11/3, 2012 at 8:56 Comment(0)
C
12

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:

var Globals = <?php echo json_encode(array(
    'active_user_id' => $active_user->id,
    'token' => $token,
    'hash' => $hash,
)); ?>;

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

Then use data- attributes for storing real data associated with containers. You won't need post1/post2/post3-like classes and separate event handlers for them:

<div data-post-id="10">here is something</div>

instead of eg.:

<div class="post10">here is something</div>

How to read globals and data- attributes from external JS file

And then your JavaScript may look 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 this should be sufficient (although I did not test it).

Conjure answered 11/3, 2012 at 9:20 Comment(2)
Great answer! Thank you so much. I thought about using the data- attribute but hesitated as I wasn't sure about it's support.Cassandry
I totally forgot what i searched, but came across this answer and it finally cleared my missing knowledge how to use the data- attributes.Eleaseeleatic
M
3

You could always call the function with parameters from PHP:

somefile.js:

function func(params) {
    //params is now from PHP
    //params.foo == "bar"
}

somefile.php:

<?php
    $params = array('foo' => 'bar');
?>

<script type="text/javascript">
$(function() {
    func(<?php echo json_encode($params); ?>);
});
</script>

I tend to go with this approach because it avoids global variables while allowing easily transporting variables.

I like to use json_encode also because anything valid JSON is valid JS meaning you don't have to worry about escaping ' or " if you use a string and echo PHP inside of it.

Mariken answered 11/3, 2012 at 9:6 Comment(0)
K
1

The way I usually do this is using a few variables in the page itself, then the included JavaScript access those variables.

In your main page:

var post_id=<?php echo $post->id; ?>;

Then in your included JS file:

data: { post_id: post_id,
Kidder answered 11/3, 2012 at 9:1 Comment(0)
S
0

You cannot put it into an external .js file if you still want to include PHP variables. But you can put the code into a separate PHP file that generates valid Javascript output (including content-type in the header set to "text/javascript"!).

In your first PHP file you can refer to the second PHP file generating the Javascript code with

<script src="path/to/generateJS.php" type="text/javascript"></script>
Subdual answered 11/3, 2012 at 9:5 Comment(1)
I just tried this. Chrome is happy, but Firefox is not. It appears that even though the php file has "header('content-type: text/javascript')" apache is still calling it 'text/html'. I'm going to combine this with Ethan's response above.Hetero
B
0

I dont know if a way exists. But if you manage to include variables in external js files, it means that these files will have to be processed as php scripts rendering those variables rather than just rendering them as static files. This will affect performance adversely.

One way you can still use external JS file is declaring a function and passing parameters to it from inline javascript. You code would look like:

<script>
bindPost(<?php echo $post->id; ?>,<?php echo $active_user->id; ?>,'<?php echo $hash; ?>');
</script>

where your bindPost is declared in external JS file and handles the parameters well.

Branny answered 11/3, 2012 at 9:6 Comment(0)
G
0

Without adding a lot more complexity, the easiest way to do this is to have the server treat the Javascript file as a PHP file, so that you can define the PHP variables in that file and then echo them exactly as you're doing in the code in your question.

On apache, that means creating a .htaccess file and adding the follwing line to it:

AddType x-httpd-php .js

(Note that this will process all your javascript files as PHP. If you only want to process some of your Javascript files as PHP you'd need to make a narrower .htaccess rule.)

Gladwin answered 11/3, 2012 at 9:11 Comment(1)
This could lead to problems with other files and code down the line.Stockyard

© 2022 - 2024 — McMap. All rights reserved.