Including PHP Variables in an External Js File

Access PHP var from external javascript file

You don't really access it, you insert it into the javascript code when you serve the page.

However if your other javascript isn't from an external source you can do something like:

<?php
$color = "Red";
?>
<script type="text/javascript">var color = "<?= $color ?>";</script>
<script type="text/javascript" src="file.js"></script>

and then in the file.js use color like so:

alert("color: " + color);

Including PHP variables in an external JS file?

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

calling php variable in external.js file

The possible reason that your code isn't working are:

  1. You haven't embedded jQuery library and been using $() identifier
  2. Your PHP variable $phpValue is empty

The following code works:

var user = $("#myPhpValue").val();alert ("the user is "+user);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<input type="hidden" id="myPhpValue" value="mike">

PHP variable inside a js file

Don't forget to properly escape your variables before passing them to JavaScript. Use json_encode() for this, as it escapes and encodes your values in a way suitable for using with JavaScript:

test=<?php echo json_encode($country) ?>;

Never simply send the variable un-encoded, as it might break things, or, worse, if the value comes from untrusted sources, compromise your security.

Also, rename your file to .php instead of .js if you want to be able to insert dynamic PHP code inside it.

access php variable into external javascript file

Pass it as a parameter:

<input type="submit" onclick="func('<?php echo $var; ?>');">

in test.js:

function func(param){
console.log(param); // contents of $var
}

Or set it globally:

<script>
var param = "<?php echo $var; ?>";
</script>

How to pass PHP value to external JavaScript file

Before you call your external JavaScript file, define your variables using PHP:

<script type="text/javascript">
var site_url = '<?php echo site_url(); ?>';
var current_url = '<?php echo current_url(); ?>';
</script>
<script type="text/javascript" src="file.js"></script>

In your external file.js you can now use site_url as a variable.

Most efficient way to pass PHP variables to external JavaScript (or jQuery) file

About question 1: use JSON_HEX_TAG in json_encode()

  • Example 1
    Consider this simple piece of code.

    <script>
    <?php $myVarValue = 'hello world'; ?>
    var myvar = <?php echo json_encode($myVarValue); ?>;
    alert(myvar);
    </script>

    Output:

    <script>
    var myvar = "hello world";
    alert(myvar);
    </script>

    It alerts hello world. Good.

  • Example 2
    Let's try having </script> as the string.

    <script>
    <?php $myVarValue = '</script>'; ?>
    var myvar = <?php echo json_encode($myVarValue); ?>;
    alert(myvar);
    </script>

    Output:

    <script>
    var myvar = "<\/script>";
    alert(myvar);
    </script>

    It alerts </script>. Good.

    As you can see, the slash (/) is correctly escaped as \/,

  • Example 3
    Now, consider this very special string: <!--<script>

    <script>
    <?php $myVarValue = '<!--<script>'; ?>
    var myvar = <?php echo json_encode($myVarValue); ?>;
    alert(myvar);
    </script>

    Output:

    <script>
    var myvar = "<!--<script>";
    alert(myvar);
    </script>

    Surprisingly, it does not alert anything, and there's nothing in the error console. What?!

    If you check JSON's spec, none of the characters in <!--<script> need to be escaped, so what went wrong?

    JSON string

    Image adapted from json.org

For a complete and well explained answer, read this amazing Q & A. In short, it turns out that having
<!--<script> in a <script> block confuses the HTML parser. PHP actually did its job correctly in json_encode();
you just can't have a <!--<script> there, even though it is a perfectly valid JavaScript string!

I did a few simple tests myself. The browsers actually ignore everything after <!--<script>, so if it happens in the middle of a page,
the entire second half of the page is gone! I'm not sure if someone can actually inject something malicious there to, say, execute arbitrary
code, but that's bad enough.

Also,

  • If you have not just a string in $myVarValue, but a complex object like array("key" => array("one", "and<!--<script>two", 3)), which includes <!--<script>, it's still bad.
  • If you have a plain HTML file (i.e. no PHP) and you have <!--<script> anywhere (even in a JavaScript comment) in your <script> block, it's also bad.
  • If you are using other, non-PHP, server-side programming languages, and produced <!--<script>, it's bad too.
  • If your PHP is outputting JavaScript directly (Content-type: application/javascript), it's actually ok [1].

The solution? Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0).

<script>
<?php $myVarValue = '<!--<script>'; ?>
var myvar = <?php echo json_encode($myVarValue, JSON_HEX_TAG); ?>;
// ^^^^^^^^^^^^^^
alert(myvar);
</script>

Output:

<script>
var myvar = "\u003C!--\u003Cscript\u003E";
alert(myvar);
</script>

It alerts <!--<script>. Hurray!

It works because there's no more <!--<script> in the output, so no more HTML parsing problems.

Note: you don't need JSON_HEX_TAG if you're not printing into a <script> block.


[1] Here, "ok" merely means it is free from the <!--<script> issue. Dynamically generating external JavaScript files is not recommended as it has tons of disadvantages, such as those stated here, here, here.


About question 2: initial page load time

Actually, it's rather obvious. If the time needed to obtain the value of $myVarValue is long
(e.g. you're fetching lots of data from DB), PHP will have to wait, so is the browser, and the user.
That means longer initial page load time. If you load the data later with Ajax instead, they won't have
to wait to see the initial result, but then, the Ajax call would be an extra HTTP request, so it
means more workload to the server, and more load to the network.

Of course, each method has its pros and cons, so you have to decide. I suggest reading this excellent Q & A.



Related Topics



Leave a reply



Submit