简体   繁体   中英

Updating select/option elements value using AJAX/PHP/SQL

Little background,

I have a two dynamic select/option drop down which is echoed from PHP using sql queries.

If first drop box is selected the second drop box will contain information relevant to the first drop box, for example first drop box (console) second drop box (ps4/xbox one) etc. All this information is stored to a database.

If user select the first drop box javascript/AJAX sends that information to PHP/server, in PHP I then create a sql query and echo back all the available select/option for the second drop box.

However I am a bit stuck as I am not sure if this is the right way to implement the tags.

Nothing is showing on the option field.

UPDATED,

The first Drop box is working fine, the problem is the second one, with id sub_cat.

Javascript AJAX:

 function subCatActivation(i) {
      var selectedBox = document.getElementById("Cat" + i);
      var val = selectedBox.options[selectedBox.selectedIndex].value;
      var hr = new XMLHttpRequest();
      var url = "parse_receive_select.php";
      hr.open("POST", url, true);

      hr.setRequestHeader("Content-type", "application/x-www-form-urlendcoded");

      hr.onreadystatechange = function () {
          if (hr.readyState == 4 && hr.status == 200) {
                var return_data = hr.responseText;
                document.getElementById("opt").innerHTML = return_data;
          }
      }
      hr.send(val);
 }

HTML

<select name="Cat" id="Cat" onchange="subCatActivation('')" onclick="realTimeChange(this.id)">
    <option value="title">Main Category</op
    <?php echo $option?>
</select>
<select name="sub_cat" id="sub_cat">
    <option value="Non-Use">Sub-Category</option>
    <div id="opt"></div>
</select>

PHP

    if(isset($_POST['val'])){
        $mainCat = $_POST['val'];
        $subOption = '';
        $subName = [];
        include"../storeSQL/sql_Connection.php";
        $sql = "SELECT SUB_CAT FROM CATEGORIES WHERE CAT = '$mainCat' GROUP BY SUB_CAT";
        $getQuery = $connection->query($sql);
        $i = 0;
        while($row = $getQuery->fetch_array()){
        $subName[$i] = $row['SUB_CAT'];
        $subOption .= "<option value='$subName[$i]'>$subName[$i]</option>";
        $i++;
    }
    echo $subOption;
}

Use key value pair inside send function

 hr.send("val="+val);

And for now use sub_cat to append option tag

  document.getElementById("sub_cat").innerHTML = return_data;

And then add first option also before return_data

As you are not sending any key here, this below code will always fail and not go to if block

 if(isset($_POST['val'])){

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