title: Is it bad practice to echo javascript with php
body: <p>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?</p>
  
  <p>Here's a code snippet of what I'm doing.</p>
  
  <pre><code>&lt;?php
  
          $script = "
                      &lt;script&gt;
                      $(document).ready(function(){
                          $('".$trigger."').".$action."(function() {
                          ".$js_variables."
                              var ajax_load = '';
                              var loadUrl = '".$this-&gt;controller_path."';
                              var action = $(this).attr('id');
  
                              $('".$this-&gt;parent."')
                              .hide(2)
                              .html(ajax_load)  
                              .load(loadUrl, {action: action, ".$post_mapper."})
                              .fadeIn(800);
                          });
                      });
                  &lt;/script&gt;
          ";
  
        echo $script;
  
  ?&gt;
  </code></pre>
  
  <p>Edit: Using a singleton class would also allow me to use <code>$(document).ready()</code> or the shortcut version <code>$(function(){})</code> 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?</p>