title: load JS function before PHP validation
body: <p>I'm trying to (echo) call a javascript function from PHP when the form is submitted. I have an error that <code>function is not defined</code>. I do understand that PHP is loaded before Javascript, therefore, the function is not defined in PHP call. </p>
  
  <p>I could create <code>onclick</code> even in the HTML section but the example below is part of a bigger program and PHP script is in a separate file which is included at the top of the HTML page, the function will also receive different parameters and perform different operations when called and it will be an AJAX function. Also, I have some variables loaded as page renders and I only want to call the JS function at a certain point in the program. Moving PHP to the bottom is not elegant as I would have to add some PHP at the top some at the bottom to have all variables included.</p>
  
  <p>Is there a way to include the PHP part at the top and still call an AJAX function whenever required with a range of parameters? Or even better what is the best way of doing this sort of thing? I believe echo'ing javascript through PHP is not the best practice. </p>
  
  <pre><code>&lt;?php
  
  if (isset($_POST['a'])) {
    echo "&lt;script type='text/javascript'&gt;example('hello');&lt;/script&gt;";
    echo "&lt;script type='text/javascript'&gt;printSome(0,0);&lt;/script&gt;";
  }
  
  ?&gt;
  
  &lt;!DOCTYPE html&gt;                             
  &lt;html&gt;
  &lt;body&gt;
  
  &lt;form method="post"&gt;
    &lt;input type="text"&gt; 
    &lt;input type="submit" name="a"&gt;
  &lt;/form&gt;
  
  &lt;/body&gt;
  
  &lt;script type='text/javascript'&gt;
    function example(variable)
    {
      window.alert(variable);
    }
  
    function printSome(type, quantity)
    {
     return $.ajax({
     url                   : 'http://localhost/printDoc.php',
     type                  : 'POST',
     dataType              : 'json',
     data                  : {
                                DTStype      : type,
                                DTSquantity  : quantity
                             },
     cache                 : false
  });
  }
  
  &lt;/script&gt;
  &lt;/html&gt;
  </code></pre>