简体   繁体   中英

Script tag not working in php file

I have seen some post related to this, but could not get much help there.

I'm trying to pass an array from php file to a js file here is the code in php file

 <!DOCTYPE html > <html > <head> ------ </head> <body onload="gotofunction()"> <?php session_start(); $_SESSION['street']= $this->street; $_SESSION['city']= $this->city; $_SESSION['state']= $this->state; $_SESSION['zip']= $this->zip; ?> <script type="text/javascript"> function voodoo(){ alert('alert in voodoo'); // 1st alert document.contents.submit(); } </script> </body> </html> <?php echo "php text"; //1st echo $var= json_encode($this->variable); ?> <script type="text/javascript"> var data = { var1:'<?php echo $this->variable;?>', path:'<?php echo $this->path;?>' } </script> 

and the js file

 function gotofunction(){ alert('alert number1'); //1st alert alert(' data '+data.var1 ); //2nd alert $.post(data.path+'res/data_controller/tablog1', {'var':data.var1},function(data){ $('#pos1').html(data); }); } 

the problem I'm facing is that in the js file, the error comes as "data is not declared" and also the 2nd alert in js file doesn't work. In the php file php echos can be seen but not the alerts.

Thanks in advance

Add JS before the body like this.

<?php
  session_start();
  $_SESSION['street']= $this->street;
  $_SESSION['city']= $this->city;
  $_SESSION['state']= $this->state;
  $_SESSION['zip']= $this->zip;
?>
<!DOCTYPE html >
<html >
<head> ------ </head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">
      var data = {
    var1:'<?php echo $this->variable;?>',
    path:'<?php echo $this->path;?>'
    }
function gotofunction(){

    alert('alert number1');     //1st alert
    alert(' data '+data.var1 ); //2nd alert
    $.post(data.path+'res/data_controller/tablog1', {'var':data.var1},function(data){
     $('#pos1').html(data);
    });
    }

</script>

<body onload="gotofunction()">



<script type="text/javascript">
  function voodoo(){
    alert('alert in voodoo');  // 1st alert
   document.contents.submit();
}

</script>
</body>
</html>

<?php echo "php text";   //1st echo
  $var= json_encode($this->variable);
  ?>

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