Hi all,
I am going crazy here trying to call a javascript function from PHP. A very basic version of what I want to do is:

$new = htmlspecialchars("<script type=\"text/javascript\">alert('Clicked on link!');</script>", ENT_QUOTES);
echo $new;

All this does is display <script type="text/javascript">alert('Clicked on link!');</script> (in plain html text) at the top of my webpage rather than call the javascript function. I have also tried this without the htmlspecialchars but I still cant call it so It must be something I am doing wrong with the escaping. I have read through the manual looking at all the functions and trying a "\" before some of the characters etc but feel really really lost. Can someone please advise me on this and what I can try next. I keep running into trouble with escaping characters, assuming a \ before each character works

    $new = '<script type="text/javascript">alert("Clicked on link!");</script>';
    echo $new;
    

      Hi devinemke, thanks for the quick reply. it still doesnt work for me however when I put in my full string:

      $new = '<script type="text/javascript">showAddress("address1"); return false</script>';
      echo $new;
      

      If i run the function in the head i.e. <script type="text/javascript">showAddress("address1"); return false</script> it works perfectly however. Have yo any other ideas what I am doing wrong

      I have also tried:

      $new = "<script type="text/javascript">showAddress('address1'); return false</script>";
      

      and

      $new = "<script type=\"text/javascript\">showAddress('address1'); return false</script>";
      

        You can't call Javascript from PHP. You can only use PHP to formulate Javascript code prior to the page loading. You could, however, create an array of values with PHP and use an HTML action to call the Javascript function later. For example:

        <script>
        function printArray()
          {
          var my_array = new array();
        
          <?php
          for($x = 0; $x < 10; $x++)
            {
            echo "var my_array[$x] = $x";
            }
          ?>
        
          for(x = 0; x < 10; x++)
            {
            document.div1.text = "Array value " + x + " = " + my_array[x] + "<br>";
            }
          }
        </script>

        Actually, that may not even be valid Javascript code, but I'm just making a point. 🙂

          Write a Reply...