5

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:

Controller to populate the first dropdown:

@RequestMapping(value = "/post_project", method = RequestMethod.GET)
    public String postProjectPage(Model model) {
        Project project = new Project();
        List<Category> categoriesList = categoryService.getAllCategories();
        model.addAttribute("projectForm", project);
        model.addAttribute("categoriesList", categoriesList);
        return "post_project";
    }

JSP:

<form:form id="post_project" action="/post_project" method="post" modelAttribute="projectForm"> 
    <form:select class="form-control" id="selectCategory" path="category">
         <option value="">-Select-</option>
         <form:options items="${categoriesList}" itemValue="id" itemLabel="category_name"/>
    </form:select>

For the subcategories I have the following controller:

@RequestMapping(value = "/post_project", method = RequestMethod.POST)
    public @ResponseBody  List<Subcategory> getAllSubcategories(@RequestParam(value="categoryId") int categoryId) {
        return categoryService.getAllSubcategories(categoryId);
    }

JSP:

  <form:select class="form-control" id="selectSubcat" path="subcategory">
       <option value="-1" label="-Select-"/>
    </form:select>

For populating the second dropdown I used AJAX, but I am very new with this and I don't know if it is right.

("#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<data.length; i++){
                    option = option + "<option value='"+data[i].id + "'>"+data[i].subcateogory_name + "</option>";
                }
                slctSubcat.append(option);
            },
            error:function(){
                alert("error");
            }

        });
    });

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?

1
  • Are you getting the request at the backend? Commented Jul 2, 2017 at 14:23

2 Answers 2

3

Make you request as a GET:

("#selectCategory").change(function(){
    var categoryId = $(this).val();
    $.ajax({
        type: 'GET',
        url: "/categories/" + categoryId,
        success: function(data){
            var slctSubcat=$('#selectSubcat'), option="";
            slctSubcat.empty();

            for(var i=0; i<data.length; i++){
                option = option + "<option value='"+data[i].id + "'>"+data[i].subcateogory_name + "</option>";
            }
            slctSubcat.append(option);
        },
        error:function(){
            alert("error");
        }

    });
});

Server Side controller method:

@RequestParam is used to get the query parameters. So, it would be like ..../post_project?categoryId=1

Instead of @RequestParam use @PathVariable as below:

So to get the subcategories, you have @RequestMapping like .../categories/1

@RequestMapping(value = "/categories/{categoryId}", method = RequestMethod.GET)
public @ResponseBody  List<Subcategory> getAllSubcategories(@PathVariable("categoryId") int categoryId) {
    return categoryService.getAllSubcategories(categoryId);
}
Sign up to request clarification or add additional context in comments.

5 Comments

But the first GET request for /post_project is for displaying the page and the categories in the first dropdown. I can't have 2 GET requests for /post_project. How do I do then? Sorry, I am new at this.
That's fine to have another GET. For the first request, to display the page, you can use /post_project and after loading the page and on the select on change event you can call to another URL, like /categories/{categorId}.
I have a form for posting a project and when a category is selected I want the second dropdown to be populated with the subcategories on the same page. If I use another URL like /categories/{categoryId} that doesn't mean that I have to display them on another page?
Another will be calling through AJAX and your controller method shouldn't return a view but JsON response.
First call will load your JSP from /post_project:GET. This will have your first select element and once selected it will make an AJAX request to URL /categories/{categoryId} which will return JSON object for sub categories with that ID. Once the request is successful, you can update the DOM/second select element with the data/response.
0

Try to add the contentType & dataType to your Ajax Call :

` ....
  $.ajax({
        type: 'POST',
        url: "/post_project",
        data: {"categoryId" : categoryId},
        contentType:"application/json; charset=utf-8"
        dataType:"json",
........` 

and change your controller to Post a Json Request :

@RequestMapping(value = "/post_project", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.