0

I'm working on a php code and had this headache I had been battled for weeks. I have a search option list using <select>, and if I choose one option, it automatically open another search option list, and the proceed keeps on going. A simple version of it could be found here:

<?php 
echo "<form name='form1' method='post' action=".$_SERVER["PHP_SELF"].">";
echo "<select name='select1' onchange='submit()'>";
echo "<option value=''> default </option>";
echo "<option value='a'> a </option>";
echo "<option value='b'> b </option>";
echo "</select>";

if(isset($_POST["select1"])) {
    echo "<select name='select2' onchange='submit()'>";
    echo "<option value='c'> c </option>";
    echo "<option value='d'> d </option>";
    echo "</select>";
    if(isset($_POST["select2"])) {
        echo "<select name='select3'>";
        echo "<option value='e'> e </option>";
        echo "</select>";
    }
}
echo "</form>";

The search result number is: X
?>

All option data and search result number are pulled from SQL Database and changed depend on $_POST["select1"] and $_POST["select2"].

My problem is, for example, if I choose a (select1) -> c (select2) -> e (select3), then change my mind and choose b (select1), $_POST["select2"] is still set, thus making select3 visible and search result is wrong.

The best answer I can come up with it to unset $_POST["select2"] if the value of select1 changes, that means with onChange function from JavaScript.

My failed attempt:

Any help would be appreciated.

Riji
  • 340
  • 2
  • 10
  • Why do you want to use `unset` for this? This is not possible, as PHP and Javascript run independently. You should use AJAX for this – Nico Haase Apr 23 '19 at 07:27
  • How can I achieve my goal with AJAX then? Can you give me some hint to begin with? I was reading https://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript/23741119 but I still don't have any idea how to apply my sql-related php code into AJAX. – Riji Apr 23 '19 at 07:46
  • 1
    Well, you have to write some code for that :) There is no such thing as a global tutorial for this question, but you could start with https://stackoverflow.com/questions/22991067/populating-a-select-box-using-jquery-ajax-and-php – Nico Haase Apr 23 '19 at 07:49

0 Answers0