Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to echo javascript with php

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?

like image 796
jerry Avatar asked Sep 03 '26 10:09

jerry


2 Answers

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.

like image 150
zzzzBov Avatar answered Sep 06 '26 00:09

zzzzBov


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>
like image 44
James Avatar answered Sep 06 '26 00:09

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!