Skip to content Skip to sidebar Skip to footer

Unable To Populate Chained Dropdown List With Ajax And Javascript

I'm new to Ajax, and programming in general, and I am currently in the midst of learning as I go. My Goal I am currently trying to create a chained dropdown list with the first dro

Solution 1:

I would recommend 2 changes -

1.Load your Category select options on page load, instead of using onclick.
-Add onload="getcategory()" to your body tag.

2.Load your SubCategory select options on change of Category.
-Add onchange="getsubcategory(this)" to your <select id="category">, and remove the onclick="getsubcategory(cat)" from your <select id="subcat" >
-Then use var catval = cat.options[cat.selectedIndex].value; in your getsubcategory() to get the selected value.

It would now look like -

...
<!DOCTYPE html>
<html>
  <head>
    <script>
    function getcategory() {
      var xmlhttp;
      if(window.XMLHttpRequest) {
        //code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp= new XMLHttpRequest();
      } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange=function() {
        if(xmlhttp.readyState==4 && xmlhttp.status==200) {
          document.getElementById("category").innerHTML=xmlhttp.responseText;
        }
      }
      xmlhttp.open("GET","AddItemCat.php","true");
      xmlhttp.send();
    }
    function getsubcategory(cat) {
      var xmlhttp;
      var catval = cat.options[cat.selectedIndex].value;
      if(window.XMLHttpRequest) {
        //code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp= new XMLHttpRequest();
      } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange=function() {
        if(xmlhttp.readyState==4 && xmlhttp.status==200) {
          document.getElementById("subcat").innerHTML=xmlhttp.responseText;
        }
      }
      xmlhttp.open("GET","AddItemSubCat.php?cat="+catval,"true");
      xmlhttp.send();
    }
  </script>
</head>
<body onload="getcategory()">
  <form action="<?PHP echo $_SERVER['PHP_SELF'] ?>" name="additem" enctype="multipart/form-data" method="POST">
    <table>
    <tr>
      <td>Select Category: </td>
        <select id="category" onchange="getsubcategory(this)">
          <option value=""></option>
        </select>
      </td>
    </tr>
    <tr>
      <td>Select SubCategory</td>
      <td>
        <select id="subcat">
          <option value=""></option>
        </select>
      </td>
    </tr>
  </table>
  </form>
</body>
</html>

Post a Comment for "Unable To Populate Chained Dropdown List With Ajax And Javascript"