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

javascript.php contains codes like this:

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

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.


Here is the approach I would use:

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

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

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

$(document).ready(function() {

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"

you can add:

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

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

Need Your Help

AS3/AIR - Saving an extremely large image to PNG

actionscript-3 air png sprite bitmapdata

I'm making a program for myself that can open unarranged sprite sheets, arrange them according to an XML file, and then save them as PNGs. What it does is it loads the unarranged sheet and puts it ...

Authlogic User Data

ruby-on-rails ruby ruby-on-rails-3 model authlogic

I keep trying to find a way to associate data with users in authlogic. I've tried everything I can think of but nothing seems to grab the data I'm trying to associate with it. Does anyone have an e...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.