name_masked
name_masked

Reputation: 9803

Calling Javascript function from PHP function

Below is my code in a single PHP file named testOne.php

<html>
<head>
     <script type="text/javascript">
          function testAlert(firstValue, secondValue)
          {
               alert ("Passed: "+firstValue+secondValue);
          }
     </script>
</head>
<body>
  ....
</body>
</html>

<?php
     function testPassedValues($One, $Two)
     {
        echo "<input type = \"button\" onclick = \"testAlert($One[2], $Two[2])\">Click Here!</input>";
     }

     $link = mysql_connect("localhost", "root", "");
     if (mysql_select_db("myDatabase", $link))
     {
         $result = mysql_query("SELECT * FROM MYTABLE");
         while($currRowOne = mysql_fetch_row($result) &&
               $currRowTwo = mysql_fetch_row($result))
         {
             testPassedValues($currRowOne, $currRowTwo);
         }
     }
?>

To help in understanding, I am calling a javascript method testAlert() from the PHP function testPassedValues(). However, I am not sure what the issue is since the call is not successful. In Mozilla(Firebug), I don't find any issues and in Chrome->Developer Tools, I get the error Uncaught Syntaxerror: Unexpected token ILLEGAL in the console.

Can anyone please help me as to the root cause here?

Upvotes: 0

Views: 2363

Answers (2)

Borealid
Borealid

Reputation: 98559

I don't think you've fully understood where and how JavaScript and PHP are executed.

PHP is run on the server. It generates an HTML page (potentially containing JavaScript), which is then sent to the client. The PHP is now finished.

The client's web browser then runs the JavaScript.

To debug your JavaScript problem, take a look at the web page the client actually saw. If Firebug is reporting a problem, that's where it is.

Upvotes: 4

Hamish
Hamish

Reputation: 23354

Most likely the values of $One[2] and $Two[2] are strings, so the generated HTML is:

<input type = "button" onclick = "testAlert(string one, string two)">Click Here!</input>

Which is obviously invalid javascript.

Enclose the parameters in quotes:

echo "<input type = \"button\" onclick = \"testAlert('$One[2]', '$Two[2]')\">Click Here!</input>";

You should also correctly escape the of $One[2] and $Two[2] values for HTML and JavaScript, so that you don't introduce XSS flaws or errors when a string contains an apostraphe. I'll leave that up to you to figure out.

Upvotes: 2

Related Questions