1

I am a beginner here so the question is maybe stupid, there is a POST data passed from a html form, and I want it to print some string based on that value, lets say

$_POST['veggie']

The data could be 1,2,3. and I want it to print "apple", "banana", "carrot". I have tried using JavaScript but it will not read POST data

 <script>
    whatVeggie(){
        if ($_POST['veggie'] == 1) {
            document.getElementById('myVeggie').innerHTML="apple";
        } else if ($_POST['veggie'] == 2){
            document.getElementById('myVeggie').innerHTML="banana";
        } else if $_POST['veggie'] == 3){
            document.getElementById('myVeggie').innerHTML="carrot";
          }
        }
 </script>

<body onload="whatVeggie();">
I like to eat<p id="myVeggie"></p>
</body>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101

1 Answers1

0

No need for the JS here you could use simply the PHP code :

<?php 
    $id='default_id';
    $veggies = ["","apple","banana","carrot"];

    if ( isset($_POST['veggie']) ){
       $id = $veggies[$_POST['veggie']];
    }
?>

<body>
     I like to eat<p id="<?php echo $id; ?>"></p>
</body>

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101