title: Populate dropdown based on another dropdown selection Spring MVC AJAX
body: <p>I have 2 dropdowns: one for categories and one for subcategories. Based on what category I select on the first dropdown I want that the second dropdown to be dynamically populated with the subcategories of the selected category. This is what I have so far:</p>
  
  <p>Controller to populate the first dropdown:</p>
  
  <pre><code>@RequestMapping(value = "/post_project", method = RequestMethod.GET)
      public String postProjectPage(Model model) {
          Project project = new Project();
          List&lt;Category&gt; categoriesList = categoryService.getAllCategories();
          model.addAttribute("projectForm", project);
          model.addAttribute("categoriesList", categoriesList);
          return "post_project";
      }
  </code></pre>
  
  <p>JSP:</p>
  
  <pre><code>&lt;form:form id="post_project" action="/post_project" method="post" modelAttribute="projectForm"&gt; 
      &lt;form:select class="form-control" id="selectCategory" path="category"&gt;
           &lt;option value=""&gt;-Select-&lt;/option&gt;
           &lt;form:options items="${categoriesList}" itemValue="id" itemLabel="category_name"/&gt;
      &lt;/form:select&gt;
  </code></pre>
  
  <p>For the subcategories I have the following controller: </p>
  
  <pre><code>@RequestMapping(value = "/post_project", method = RequestMethod.POST)
      public @ResponseBody  List&lt;Subcategory&gt; getAllSubcategories(@RequestParam(value="categoryId") int categoryId) {
          return categoryService.getAllSubcategories(categoryId);
      }
  </code></pre>
  
  <p>JSP:</p>
  
  <pre><code>  &lt;form:select class="form-control" id="selectSubcat" path="subcategory"&gt;
         &lt;option value="-1" label="-Select-"/&gt;
      &lt;/form:select&gt;
  </code></pre>
  
  <p>For populating the second dropdown I used AJAX, but I am very new with this and I don't know if it is right. </p>
  
  <pre><code>("#selectCategory").change(function(){
          var categoryId = $(this).val();
          $.ajax({
              type: 'POST',
              url: "/post_project",
              data: {"categoryId" : categoryId},
              success: function(data){
                  var slctSubcat=$('#selectSubcat'), option="";
                  slctSubcat.empty();
  
                  for(var i=0; i&lt;data.length; i++){
                      option = option + "&lt;option value='"+data[i].id + "'&gt;"+data[i].subcateogory_name + "&lt;/option&gt;";
                  }
                  slctSubcat.append(option);
              },
              error:function(){
                  alert("error");
              }
  
          });
      });
  </code></pre>
  
  <p>Of course it does not work. When I select a cateogry nothing shows up in the second dropdown. I don't know what to do anymore and I've tried everything. Can someone please tell me what I am doing wrong?</p>