6

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.

Cleankod
  • 2,220
  • 5
  • 32
  • 52

3 Answers3

14

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>
Ivan
  • 14,692
  • 17
  • 59
  • 96
  • I like it! I mean I have a lot of libraries which are generating JavaScript code by concatenate strings, which after a while gets messy. But this I could resolve with the View in MVC. I'll try that, thanks! – Cleankod Mar 01 '11 at 10:25
  • 1
    You don't even need the `RewriteRule` (and some hosts don't permit it). Just use `header("Content-Type: text/javascript");`, it's enough. – Felix Mar 02 '11 at 08:35
  • Yes, but what about caching in browsers? I have bad experience with caching the dynamically generated file contents (js, css, images). – Cleankod Mar 02 '11 at 10:43
  • Set pragma to no cache if you have it by default. I've never had any problem with this technique. – Ivan Mar 03 '11 at 17:42
  • Yes, but I want browsers to cache dynamically generated file and your solution seems to disable it. Another words - how can I generate JS file (orr CSS, whatever) and force Browser to treat it as usual file (cache and everything). – Cleankod Mar 31 '11 at 18:18
4

I was trying to make my server do an API call and embed it in a html to have javascript process it.. of course put whatever you want in the echo..

<?php
// a_local_file.php
Header("content-type: application/x-javascript");

echo file_get_contents('http://some_remote_script');
?>

And use this to refer to it in HTML...

<script type="text/javascript" src="a_local_file.php"></script>

The api call should return valid javascript, otherwise add what you need to make it valid; this is often the troublesomepart with working with json from api calls. Stripslashes, trim, and other string functions may be of use .. but often pesky foreign characters seep in and can set off php errors based on your php setup.

redcap3000
  • 928
  • 1
  • 8
  • 15
2

You might want to check out json_encode and json_decode.

Felix
  • 88,392
  • 43
  • 149
  • 167
  • I am already using that but json_encode wouldn't help with inline functions, events and stuff like that. – Cleankod Mar 01 '11 at 10:26
  • 1
    @Ivan you commented on the wrong answer, but thanks :P. @Spyro no, it will not. It's just a way to transfer data between the two, which is all that you should need. – Felix Mar 02 '11 at 08:37