1

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:

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 ...):

// 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 "      <div id='" . $herald_id . "'>\n";
   echo "         " . $sca_name . "\n";
   echo "         <script type='text/javascript'>test();</script>\n";
   echo "      </div>\n";

}

This is the JavaScript code (at the bottom of the file):

<script type="text/javascript">
    function test()
    {
       alert( "Test function" );
    }
</script>

However, I get no "alert" dialog, just the text streamed out. So for the first row I get:

  <div id='1'>
     Aasa Thorvaldsdoittr
     <script type='text/javascript'>test();</script>
  </div>

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.

Ken Mayer
  • 115
  • 15
  • Possible duplicate of [How to call a JavaScript function from PHP?](https://stackoverflow.com/questions/1045845/how-to-call-a-javascript-function-from-php) – Michael Jasper Aug 01 '18 at 16:03
  • 3
    Add the function declaration to the top of the file – Zakaria Acharki Aug 01 '18 at 16:03
  • Try to add $(document).ready(function{ alert();}) – Confused Aug 01 '18 at 16:03
  • @Confused no evidence that jQuery is being used here, or that jQuery is desired. Besides, that code will just run the alert once when the page loads, which is not what OP asked for. I am tempted to comment on the irony of your username but I won't. – ADyson Aug 01 '18 at 16:03
  • 2
    How do you expect to call a function which is declared __later__ than it's call? – u_mulder Aug 01 '18 at 16:04
  • Instead of doing `test()` do `document.write('hello');` to test that JS is working. More than likely your `function test()` is defined after PHP goes through the loop. Try to define your function before the loop. – JM-AGMS Aug 01 '18 at 16:08
  • @u_mulder: in javascript, it doesn't matter whether the function is declared before or after it is used, because of "hoisting": foo() ; function foo () { alert("hoisted!") } – techjeffharris Aug 01 '18 at 16:11
  • Aha, so when the rest of the page with function definition is __not__ loaded, you can use it? – u_mulder Aug 01 '18 at 16:13
  • 1
    @techjeffharris that assumes the function has actually been rendered to the DOM, though. In this case, it hasn't yet, because the script which calls it is executing immediately, and that script is rendered before the function is rendered. See my answer. – ADyson Aug 01 '18 at 16:28

2 Answers2

3

"JavaScript code at the bottom of the file"

is the problem. Scripts are run as soon as they are added to the DOM. Things are added to the DOM in the order they are given in the HTML.

Therefore the script tags which try to call your function are added - and executed - before the script tag which actually contains the function gets added. So they try to execute a function which doesn't yet exist. If you look in your browser's Console (in the Developer Tools) you probably have some errors complaining about this.

The simple solution is to declare the script tag containing the function somewhere in your HTML before the code which tries to use it.


As an aside, it would be interesting to know what you plan to do with this function in reality - consider whether you could achieve the same effect directly by creating some markup using PHP, rather than firing off lots of JS while the page is loading.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • "In reality" I am going to be doing an Ajax call to send some mail-merge type emails (no spam ...). That code works in another PHP program just fine. – Ken Mayer Aug 01 '18 at 16:15
  • That does the trick. I have been using the code at the end of the document in other places from button "onclicks" and that worked fine, but forgot this. – Ken Mayer Aug 01 '18 at 16:16
  • you could potentially make those requests from PHP - it only has to go back to the server anyway (unless you're sending it off to a 3rd-party server or something) – ADyson Aug 01 '18 at 16:16
  • 1
    yeah onclick would be ok because that action doesn't happen until the user presses something, and that generally doesn't happen until everything is loaded. – ADyson Aug 01 '18 at 16:17
  • Problem with making the request from PHP is I have a routine designed already to be called from Ajax, so I need it to work with that, rather than having two separate sets of code that do virtually the same thing. – Ken Mayer Aug 01 '18 at 16:22
  • well that's fair enough if it's already written, just something to think about in future. Although if you made that functionality into a PHP function, you could call it from PHP direct, or from AJAX (the AJAX endpoint script would just call the same function and then return the output as JSON (or whatever) instead of a PHP variable) – ADyson Aug 01 '18 at 16:25
1

You should move the function declaration upper than it used. For example:

<script type="text/javascript">
function test()
{
   alert( "Test function" );
}
</script>
..
<?php
..
// your loop
..
?>

or

<?php
..
echo '<script type="text/javascript">
function test()
{
   alert( "Test function" );
}
</script>';
..
// your loop
..
?>