0

I saw in another post in stackoverflow that it was possible to include PHP code in HTML tag but I have this error: "Undefined index: select_years" when I use this code :

<script type="text/javascript">
   console.log(<?php echo $_POST["select_years"];?>);
</script>

SebCollard
  • 332
  • 2
  • 20
  • have you posted that variable? usually you would have an if around to check if that variable exists – Pete Jul 19 '19 at 10:43
  • 3
    you shouldn't ever mix PHP and JS - they're executed different and could lead to unexpected behaviour – treyBake Jul 19 '19 at 10:44
  • which value you are getting in $_POST["select_years"]? – suhas pandit Jul 19 '19 at 10:44
  • Once you fix the undefined index, you'll probably want to do `console.log();` for safety. – ceejayoz Jul 19 '19 at 15:18
  • What makes you think that this error is in any way related to Javascript? Why not check for array indices before using them, in the same way you would do it in pure PHP? – Nico Haase Jul 19 '19 at 15:18

2 Answers2

0

For post, get or request methods before printing or using them check if the request is submitted or not.

<?php
if(isset($_POST["select_years"])){
?>
<script type="text/javascript">
   console.log(<?php echo $_POST["select_years"];?>);
</script>
<?php
}
?>
Rohit Guleria
  • 72
  • 1
  • 12
-1
 <?php
 $select_years="";
 if(isset($_POST["select_years"])){
    $select_years=$_POST["select_years"];
 }
 ?>

 <script type="text/javascript">
 console.log("<?php echo $select_years;?>"); //Added Double Quotes
 </script>

Try This, works for sure

Brindha Baskaran
  • 185
  • 2
  • 16