Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - generating JavaScript

I am working on a project which has a lot of JavaScript. I think that generating simple strings and putting them between "<script>" tags is not the best way to do it.

Are there any better approaches to generate JavaScript objects, functions, calls etc? Maybe some convering classes (from PHP to JavaScript) or maybe there are design patterns I should follow?

PS. If it has any relevance - I am using MooTools with MochaUI (with MochaPHPControl).

Thanks in advance for the help.

like image 202
Cleankod Avatar asked Mar 01 '11 08:03

Cleankod


1 Answers

The best approach is to think Javascript as PHP code.

The basic steps are:

  1. Create a .htaccess file that redirects all JS files (.js) to a index file.
  2. In this index file load JS file as a PHP module (require "script/$file")
  3. Modify all JS files as you need. Now you can embed PHP code.

For instance, add to your .htaccess this line:

RewriteRule \.js$ index.php

In your index.php file put something like this:

// Process special JS files
$requested = empty($_SERVER['REQUEST_URI']) ? "" : $_SERVER['REQUEST_URI'];
$filename = get_filename($requested);
if (file_ends_with($requested, '.js')) {
     require("www/script/$filename.php");
     exit;
}

And finally in your file.js.php you can embed PHP, use GET and POST params, etc:

<?php header("Content-type: application/x-javascript"); ?>
var url = "<?php echo $url ?>";
var params = "<?php echo $params ?>";

function xxxx().... 
....

In addition, a trick to skip file cache is to add a random number as javascript parameter:

<script type="text/javascript" src="scripts/file.js?a=<?php echo rand() ?>"></script>

Also, as said in a comment, if your webserver don't allow to modify the .htaccess, you can just ask for the PHP file directly:

<script type="text/javascript" src="file.php"></script>
like image 99
Ivan Avatar answered Sep 28 '22 02:09

Ivan