d-_-b
d-_-b

Reputation: 23171

What is the most efficient way to include many javascript functions (with PHP in them) in a PHP page?

In one of my sites, I need to use PHP 'foreach' to keep including some Javascript code. In this code contains PHP $variables that change within the foreach loop.

foreach ($a as $b) {
   include("javascript.php");  
}

javascript.php contains codes like this:

<script>
   $(".<?php echo $somevariable?>").something;
</script>

My question is: What is the most efficient (if any) way to load javascript that contains PHP variables?

I keep reading that it's better to call large javascript codes in a .js script rather than writing it on the page, But apparently .js files can not have PHP.

Thanks for your insight.

Upvotes: 0

Views: 171

Answers (2)

Nick Clark
Nick Clark

Reputation: 4467

Here is the approach I would use:

Create your HTML file with a Javascript variable containing $somevariable:

<html>
<head>
    <script src="my_global.js"></script>
</head>
<body>
    Foo
<script>
    var somevariable = "<?php echo $somevariable ?>";
</script>
</body>
</html>

Then have the Javascript file access this value once the page is ready (I'm using jQuery .ready() in this example):

$(document).ready(function() {
    alert(somevariable);
});

Here it is in action: http://jsfiddle.net/2zeQM/

This allows the Javascript file to be cached (it's static and not dynamic). And the dynamic data is loaded on the page being requested by the user.

You do need to be careful that the variable name you use does not get reused by any other Javascript code. To prevent problems, I would prefix the variable name. For example, instead of calling it "somevariable", I might call it "xy_somevariable"

Upvotes: 1

Ryan Potter
Ryan Potter

Reputation: 835

you can add:

header("Content-type: text/javascript");

to the top of your .php file and it will render as a .js file.

Upvotes: 1

Related Questions