title: Call Javascript Function from PHP in a loop
body: <p>I have been looking at answers to this across the web for about an hour now, and trying things based on those answers (I know this kind of issue comes up often). However, nothing I am trying is working. So an explanation first:</p>
  
  <p>I am looping through a table in PHP (in a while loop), and need to call a JavaScript function for each record in the row set returned for my table. To try to get started, I have a super basic function that just lets me know I called it ... it's not working. Here's the PHP code (the reason for the DIV tag is that I eventually want to replace the innerHTML of the DIV from the JS code I know how to do that and have done so elsewhere ...):</p>
  
  <pre><code>// the loop:
  while( $row = mysqli_fetch_array( $heralds_result ) )
  {
     $herald_id = $row["roster_id"];
     $sca_name = $row["sca_name"];
  
     // create a div for each herald as we go with its' own name (using id ...)
     echo "      &lt;div id='" . $herald_id . "'&gt;\n";
     echo "         " . $sca_name . "\n";
     echo "         &lt;script type='text/javascript'&gt;test();&lt;/script&gt;\n";
     echo "      &lt;/div&gt;\n";
  
  }
  </code></pre>
  
  <p>This is the JavaScript code (at the bottom of the file):</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      function test()
      {
         alert( "Test function" );
      }
  &lt;/script&gt;
  </code></pre>
  
  <p>However, I get no "alert" dialog, just the text streamed out. So for the first row I get:</p>
  
  <pre><code>  &lt;div id='1'&gt;
       Aasa Thorvaldsdoittr
       &lt;script type='text/javascript'&gt;test();&lt;/script&gt;
    &lt;/div&gt;
  </code></pre>
  
  <p>As the alert dialog is not displayed, it tells me the Javascript function is not being called, or there is some error that is truly not obvious to me after staring at it for a long time. This is something that shouldn't be this difficult, I am sure I have some really obvious error that someone will see as soon as they look at the code, but it's evading me completely.</p>