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>functiongetcategory() {
      var xmlhttp;
      if(window.XMLHttpRequest) {
        //code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp= newXMLHttpRequest();
      } else {
        xmlhttp=newActiveXObject("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();
    }
    functiongetsubcategory(cat) {
      var xmlhttp;
      var catval = cat.options[cat.selectedIndex].value;
      if(window.XMLHttpRequest) {
        //code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp= newXMLHttpRequest();
      } else {
        xmlhttp=newActiveXObject("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><bodyonload="getcategory()"><formaction="<?PHPecho$_SERVER['PHP_SELF'] ?>"name="additem"enctype="multipart/form-data"method="POST"><table><tr><td>Select Category: </td><selectid="category"onchange="getsubcategory(this)"><optionvalue=""></option></select></td></tr><tr><td>Select SubCategory</td><td><selectid="subcat"><optionvalue=""></option></select></td></tr></table></form></body></html>

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