简体   繁体   中英

Call Javascript function from php

I have done many attempts with posts and examples - but I'm unable to understand how to do this. I have this function in the head of my php file:

    .....
    <script type = "text/javascript" language="javascript">
    function agicol() {
    scheduler.clearAll();
    var idname$ = $idencol;  
    scheduler.load("ret_l.php?connector=true&dhx_filter[IDCol]="+idname$,"json");
    }
 </script>  
 </head>

And in the body, I use a variable like so:

  <body bgcolor="#C0DFFD" onLoad="init();">
  <?php
   if(isset($_GET['id']))
   {
   $idencol = $_GET['id'];
   echo "<script>alert($idencol);</script>";
   // Alert works properly
   // $idencol contains id sended
   }
   ?>

So, I should call function agicol() , and pass getted id $idencol .

Can someone tell me how?

Thanks in advance

You need to call the js function agicol() in the header which uses the js variable $idencol (very bad variable name here) set by php in the body.

The problem in your code is that the PHP part doesn't set the expected js variable properly. Change your PHP part like this (notice the escape \\$ I have used):

<?php
   if(isset($_GET['id']))
   {
      $idencol = $_GET['id'];
      echo "<script>";           
      echo "\$idencol = $idencol;";   //Set JS global variable you expect in the function
      echo "agicol();";               //Call the function
      echo "</script>";

   }
?>

This will solve your current problem.


But there are many better ways to do it. You can set your JS function to accept an argument and send the id through that rather than using a global variable with a bad name.

function agicol(id) {
    scheduler.clearAll();
    scheduler.load("ret_l.php?connector=true&dhx_filter[IDCol]=" + id, "json");
    }

... in PHP in the body

$idencol = $_GET['id'];
echo "<script>agicol($idencol);</script>";

load will strip out the <head> (or rather, will extract the content of the <body> and discard everything else) from the document you are loading.

Either:

  • Define your function in a JS file you just load throughout the site (this is generally the best approach)
  • Move your script to the body
  • Replace load with ajax and extract the various bits of data you care about manually

You can try something like: echo "<script>agicol();</script>"; Otherwise, you should update your javascript function to pass param.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM