3

I have a php application that makes use of a Listener class, which basically just sets up an ajax request with jquery (example below). But for some reason, echoing the javascript just seems inelegant. Is it better practice to build a singleton class for the javascript to be passed to (which could introduce coupling) or to just echo the script like I'm doing now?

Here's a code snippet of what I'm doing.

<?php

        $script = "
                    <script>
                    $(document).ready(function(){
                        $('".$trigger."').".$action."(function() {
                        ".$js_variables."
                            var ajax_load = '';
                            var loadUrl = '".$this->controller_path."';
                            var action = $(this).attr('id');

                            $('".$this->parent."')
                            .hide(2)
                            .html(ajax_load)  
                            .load(loadUrl, {action: action, ".$post_mapper."})
                            .fadeIn(800);
                        });
                    });
                </script>
        ";

      echo $script;

?>

Edit: Using a singleton class would also allow me to use $(document).ready() or the shortcut version $(function(){}) only once instead of every single time I add a listener. But I'm not sure if this is worth the extra time and effort... Any ideas?

6
  • no not at all,its equally acceptable.
    – uday
    Jun 8, 2012 at 18:41
  • I believe echoing javascript with php is quite a common practice. Whether this common practice is great is another question completely.
    – Hans Z
    Jun 8, 2012 at 18:42
  • I personally don't like the idea of mixing server-side and client-side code, however there isn't anything wrong with it.
    – Kevin B
    Jun 8, 2012 at 18:48
  • @KevinB, "there isn't anything wrong with it" i disagree. There are lots of things wrong with it most of the time. There are a few niche instances where it makes sense to echo out client-side code (JSON for instance). It's nasty to debug, and performs poorly (no way to cache inline JS).
    – zzzzBov
    Jun 8, 2012 at 19:04
  • 1
    @KevinB, just because I can write a PHP script that generates an XML file that gets interpreted in a Flash app that calls some JavaScript that sets a Cookie doesn't mean that that would even remotely resemble "best practice". There is a time and a place for dynamically generated JS, but the code provided in the question is the wrong time and wrong place.
    – zzzzBov
    Jun 8, 2012 at 19:09

4 Answers 4

8

Is it bad practice to echo JavaScript with php?

Generally: Yes

It's a common practice to echo JavaScript from php, but I highly discourage it.

In most cases you can avoid mixing languages by following a front-end MVC structure:

HTML belongs in .html* files. It's the model.
CSS belongs in .css files. It's the view.
JS belongs in .js files. It's the controller.

I find it very rare that I actually need to generate JavaScript from a server-side language. Most of the time what I actually need is to pass information that JavaScript can use.

Instead of trying to output:

<a href="#" id="foo">bar</a>
<script>
    $('#foo').click(function () {
        $.ajax('http://example.com')...
        return false;
    });
</script>

for every link, try using native HTML attributes to do most of the heavy lifting:

<a href="http://example.com/" class="ajax-link">bar</a>

and in your script you could have:

$(document).on('click', '.ajax-link', function () {
    $.ajax($(this).attr('href'))...
    return false;
});

The delegate function only has to be bound once, and can be done from a static JS file, without needing to try and inject JS into PHP code.

If you need more information passed through, use data-* attributes in conjunction with .data(...).

* or .php or any other server side language used for templating.


There are niche reasons to echo client-side code from the server. An example would be generating JSON for a JSONP API, where you need to dynamically generate the callback.

If you don't have a really good reason for generating JS with a server-side language, don't.

1

mm it's all preference... I generally would do it like this so my text editor would be able to determine what's javascript and what's PHP so it wouldn't make my eyes bleed trying to look at non-code-colored text.

<script>
    $(document).ready(function(){
        $('<?php echo $trigger ?>').<? echo $action ?>(function() {
            <?php echo $js_variables ?>
            var ajax_load = '';
            var loadUrl = '<?php echo $this->controller_path ?>';
            var action = $(this).attr('id');

            $('<?php echo $this->parent ?>')
                .hide(2)
                .html(ajax_load)  
                .load(loadUrl, {action: action, <?php echo $post_mapper ?>})
                .fadeIn(800);
            });
    });
</script>
5
  • This is how I do it as well, for the same reason: the IDE color-codes much better this way than the other.
    – Xyan Ewing
    Jun 8, 2012 at 18:51
  • 5
    -1: Not sure why anyone would vote this up, it really is a mess and can be hard to debug. Much better to keep a separation of data and interaction. Keep the JS out of your HTML files.
    – zzzzBov
    Jun 8, 2012 at 19:02
  • I didn't recommend he use JS in HTML files. I was just using the example he gave. Generally I would create functions in my JS files and just send the parameters by echoing the php values. But you can't get around to having to echo the PHP values somewhere, as they are come the server-side.
    – James
    Jun 8, 2012 at 20:51
  • @zzzzBov : I think there's people who look up the latest questions and just vote the first answer that appears there, if it vaguely resembles a reasonable answer. Early voting should be limited just like downvoting is Jun 8, 2012 at 21:55
  • 2
    -1 Really bad practices here - never add php with javascript or javascript with php... there are better ways to do what you want Oct 26, 2014 at 1:21
1

As always it depends. If you are writing a small application this mixture won't hurt you. When an application grows to a certain size, I personally find it easier to maintain, when I don't mix languages in one file.

History has taught us on the frontend not to mix HTML, JavaScript and CSS in one file. It's much better to keep them separated, otherwise it is very hard to find the right spot to look at when you try to track a bug. Mixing JavaScript and a server side language is not much better. There are still some things that come to my mind that I find ok. E.g. configuration or localization files, that need to have dynamic values.

In your example I would rather prefer to keep it separated. All you are doing can be perfectly done with (data) attributes on HTML elements and some DOM lookup. It also seems that you need to gather some information for your view that is better stored in HTML. E.g.: $action This could be derived rather simple from a form:

HTML

<from method="POST" action="/you-name-it">
  ...
</form>

JS

$(function(){
    var form = $('form');
    $.ajax( {
      type: "POST",
      url: form.attr( 'action' ),
      data: form.serialize(),
      success: function( response ) {
        console.log( response );
      }
    } );
});

The logic why this exact form is submitted, can be in JavaScript and/or PHP. It does not matter how they communicate.

1

It's perfectly acceptable, but somewhat risky - you're generating parts of the JS on-the-fly, which means you have to generate VALID JS code, or the whole code block will be killed by a syntax error.

e.g. if you're using PHP to insert the value of a PHP variable in the JS code block, something like:

<script type="text/javascript">
var last_name = '<?php echo $last_name ?>';
</script>

and $last_name happens to be O'Brien, you've now introduced a syntax error, because the generated code will be:

var last_name = 'O'Brien';
                ^^^--- string with contents O
                   ^^^^^--- unknown/undefined variable Brien
                  ^^--string followed by variable, but no operator present.
                        ^--- start of a new unterminated string containing a ;

Anytime you're inserting raw PHP-based data into a Javascript variable, you basically MUST use json_encode(), which guarantees that the generated JS data is syntactically valid JS code:

var last_name = <?php echo $last_name ?>;

Note that I didn't put any ' into this version - json_encode takes care of that for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.