3

I have got the following code:

<HTML>
    <?php
        if(isset($_GET['adjust'])){
            $adjust = true;
        }
        //More variabele declaring
    ?>
    <HEAD>
        <script type="text/javascript">
            var adjust = "<?php Print($adjust); ?>";
            //More variable 'transports'
        </script>
    </HEAD>
<!-- rest of the file -->

I would like to clean this up a little, because I have a serious amount of variables. This troubles the readability and overview of the file.

I thought of putting it all into an external JavaScript file, but it didn't seem to work.

<HTML>
    <?php
        if(isset($_GET['adjust'])){
            $adjust = true;
        }
        //More variabele declaring
    ?>
    <HEAD>
        <script type="text/javascript" src="externalJS.js"></script>
    </HEAD>
<!-- rest of the file -->

With externalJS.js:

var adjust = "<?php Print($adjust); ?>";
//More variable 'transports'

According to this question, also asked here on stackoverflow, this ain't possible.

Is there a way to do it with the knowledge of the past few years, since above question was answered? Are there other alternatives to improve the readability?

P.S.: I think it is worth mentioning I gain my php-variables from the url, txt-files and cookies.

Community
  • 1
  • 1
  • So what is the problem you are trying to solve? You want your code to be prettier? More modular? Better performance? Are you talking about just one variable or a series of variables you are trying to populate? – Mike Brant Nov 08 '13 at 21:52
  • JSON is your ally in client/server data exchanging. But actually you could just use a templater if javascript manipulating over this data is not needed. – Damiano Barbati Nov 08 '13 at 22:14

3 Answers3

5

When I have had cases where I have had to place a number of variables into javascript, I have used the approach of loading all those items into an object (or array) and outputting that data into an object/array literal in javascript.

For example:

<?php
$js_object = new stdClass();
$js_object->foo = 'some value';
$js_object->bar = 'some other value';
?>
<script type="text/javacript">;
var php_values = <?php echo json_encode($js_object); ?>;
console.log(php_values.foo);
console.log(php_values.bar);
</script>

This does a few things.

  1. Your JS output section does not need to change at all if the variables being passed need to change. Anything you want to access in JS just needs to be loaded in $js_object before the object is output to the browser via json_encode()
  2. It puts all your PHP-provided values in a neat object/array in javascript where they can be accessed.
  3. You can easily pass complex data structures in this manner (nested arrays, objects containing arrays, arrays of objects, etc.)
  4. If needed you could extend the object in javascript to provide methods, etc. to act on the data.

I would also comment that you might want to think a bit about whether you wanted to pass cookie data in this manner. Cookie data is available to javascript anyway so you may want to work with that data directly if you need to change values or such.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
0

Create an array in PHP containing the variable name (as you want it in javascript) as the key for each element, and the value as you want it in javascript as the value of each element. Then, follow this:

$myVars = array();
$myVars['adjust'] = isset($_POST['adjust']) ? true : false;
$myVars['other'] = isset($_POST['other']) ? true : false;
$myVars['another'] = isset($_POST['another']) ? true : false;

<script type="text/javascript">
    <?php
    foreach( $myVars as $k => $v ):
         echo 'var ' . $k . '="' . $v . '";'; 
    ?>
</script>

Cheers

Zhube
  • 504
  • 2
  • 6
  • Shamil, how did you get it to format like that? I tried for a few minutes, but couldn't get it to break up correctly. Thanks for any help :D – Zhube Nov 08 '13 at 22:09
  • Sorry, never mind my comment that I deleted (in case you saw it). – Ingo Bürk Nov 08 '13 at 22:28
  • I would argue that it does, indeed, improve readability. This is because it allows the variables to be defined in one chunk, one right after the next (see edited answer). – Zhube Nov 08 '13 at 22:58
  • I would consider grouping those variables into an object, otherwise your code can break easily if one `$k` happens to have the same name as another variable already used in Javascript. – Ingo Bürk Nov 09 '13 at 13:51
  • @IngoBürk: That's true, but it really depends on how you want to access the variables. To be honest, when I have done things like this in the past, it was to build an object being passed into a closure in Javascript. – Zhube Nov 09 '13 at 16:26
0

Mike Brant's approach is good here (storing everything in a json object), but to accomplish specifically what you are asking here in a more segmented way you can simply make your included javascript library a PHP file that outputs Javascript headers. Your markup would look like this:

<HTML>
    <?php
        if(isset($_GET['adjust'])){
            $adjust = true;
        }
        //More variabele declaring
    ?>
    <HEAD>
        <script type="text/javascript" src="externalJS.js.php?<?=http_build_query($_GET);?>"></script>
    </HEAD>
<!-- rest of the file -->

And then your externalJS.js.php file would look like:

<?php
header("content-type: text/javascript");
?>
var adjust = "<?php Print($adjust); ?>";
//More variable 'transports' and any other PHP/Javascript code

The header here tells the browser to treat the result as javascript despite the .php extension.

Also, if you really wanted to you could also just tell you webserver to parse js files as PHP, so that it would look for <?php ... ?> segments and execute them, so you don't even need to have a non-js extension on the file:

AddType application/x-httpd-php .js

But be careful when you do this, as it means that all javascript files (or any files in the specified directory, if you're using htaccess) will be parsed, which could open up security holes if you're not careful.


A couple of side notes:

  1. Have a look at the discussion around text/javascript vs application/javascript
  2. Don't capitalize all the tag names. Yes, HTML5 says it's OK, but the W3C recommends lowercase as a convention (both for standardization and for any possible conversion to xhtml).
  3. When just printing or echoing, first of all use lower-case (print vs Print), don't wrap the printed variable in parentheses (print and echo are language constructs, so they don't need the parentheses and there are situations where using them can cause problems), and lastly, if all you're doing in a PHP tag is printing or echoing, try using PHP echo shorthand (most webservers understand them by default): <?=$var_name;?> is the same as <?php print($var_name);?>
Community
  • 1
  • 1
Ben D
  • 14,321
  • 3
  • 45
  • 59