Get data from dropdown and update page

I have a simple webpage with a dropdown menu with a few options. I would like to be able to get the user’s selection and then output the same selection on the webpage. This is the code I have so far.

\\Pretty standard code for getting the header and title and <\div> etc.
<select id="animal" name="animal">                      
  <option value="0">--Select Animal--</option>
  <option value="Cat">Cat</option>
  <option value="Dog">Dog</option>
  <option value="Cow">Cow</option>
</select>
<?php
if($_POST['submit'] && $_POST['submit'] != 0)
{
   $animal=$_POST['animal'];
    location.reload();
}
   print_r($animal);
?>
\\Pretty standard code for getting the footer etc.

The dropdown box displays alright as shown below. It shows all the options, but when I select an option nothing happens. What I want to do is to display the selection i.e. ‘Cat’ in this case. (it’s not happening at the moment).enter image description here

Please guide me, what I am doing wrong. Eventually I hope to do other things with the dropdown. But if I can get this working I’ll have an understanding of how to get the data and update the page. The next steps are relatively easier.
Also, this piece of code is part of my template file for my page. I can upload the whole code if necessary.

Update: Eventually I want to make something like this. That is, to display relevant posts based on the user selected filters,if that helps.

2 Answers
2

How about this:

<?php

$arr = ["Cat", "Dog", "Cow" ];


if( $_POST['animal']){
   $animal=$_POST['animal'];
   echo $animal;    

}


?>

<form name="f" id="a" method="post" action="">
<select id="animal" name="animal" onchange="this.form.submit()" >                      
  <option value="0">--Select Animal--</option>
  <?php

   foreach ($arr as $a){

    if($a == $animal){
        echo "<option value="{$a}" selected >$a</option>";
    }else{
        echo "<option value="{$a}" >$a</option>";
    }

   }

   ?>

</select>
</form>

Note you may also unset the variable at the end but garbage collector is also there in PHP. This code assumes you use at least PHP 5.4+, else define te array via $arr = array("Cat", "Dog", "Cow" );

Leave a Comment