'Dynamically Populate Drop down List In Spring MVC

I am new to Spring MVC. I have two Dropdown Lists in Jsp.One for country and Other for State. As soon as i select country from list State list should be populated with respective lists.

My ajax Program:

 $("select#country").change(function() {
    var val=$("#country").val();
    alert(val);
    $.ajax({
    url : 'getstates',
    method : 'get',
    contentType: 'application/json',
     data :{
              country : val
            },

      success: function (data) {
      alert("Success Response"+ data);

      },

       error :function()
       {
               alert("error");
        }          

       });

My Controller Program:

 public @ResponseBody HashMap<String, String> 
    showstates(@RequestParam(required = false, value =      "") 
    String country,@Valid    @ModelAttribute("employee")Login employee, 
    BindingResult result, ModelMap model) {  
    HashMap<String,String>  statelist = new HashMap<String,String>();
    List<States> statelist = new ArrayList<States>();
    if (country.equals("UnitedStates")) {
    statelist.put("Al","Alaska");
    statelist.put("Tl","Texas");
    } else if (country.equals("India")) {
    statelist.put("Mh","Maharashtra");
    statelist.put("WB","West Bengal");
    statelist.put("KR","Karnataka");
    statelist.put("AP","Andhra Pradesh");
    statelist.put("TN","Tamil Nadu");
    } 
    return statelist;
    }  

I am not getting the response from controller. How to access the hasmap in jsp. Please Help me. Thanks.



Solution 1:[1]

I think you should change your method like below.

@RequestMapping(value = "/getstates", method = RequestMethod.GET)
public @ResponseBody HashMap<String, String>  showstates(@RequestParam(required = false, value = "") 
    String country,@Valid    @ModelAttribute("employee")Login employee, 
    BindingResult result, ModelMap model) {  
    HashMap<String,String>  stateMap = new HashMap<String,String>();
    //put your logic to add state on basis of country

    return stateMap;
    }  

Then on JSP you can simply iterate this map,like below.

<c:forEach items="${state.stateMap}" var="data" varStatus="status">
            <tr>
                <td>${data.value}</td>
            </tr>
        </c:forEach>

Solution 2:[2]

shearing my solution. because i was stuck in same condition.

html page

$(document).ready(function() { // for client name 

		$('#example').change(function(event) {
			var country = $("select#example").val(); // country = define value of selected option
			$.getJSON('ajaxAction0', {
				ptype : country
			}, function(data) {
				var select = $('#clientname');
				select.find('option').remove();
				$.each(data, function(key, value) {
					$('<option>').val(key).text(value).appendTo(select);
				});
			});
		});
	});
<div>
		<select class="form-control" name="example" id="example">
			<option value="0">ALL</option>
			<option th:each="dropdown : ${dropdown}" th:value="${dropdown.id}"
				th:text="${dropdown.tagName}"></option>
		</select> <select class="form-control" name="clientname" id="clientname">
			<option value="0">ALL</option>
			<option th:each="dropd : ${drpdwn}" th:value="${dropd.id}"
				th:text="${dropd.tagName}"></option>
		</select>
		<button id="w-button-search" type="button">Search</button>
	</div>

controller code for first drop down

@RequestMapping(value = "/dropdown", method = RequestMethod.GET)
public String dropDown(Model model) {
    List<Tag> data = new ArrayList<>();
    data.add(new Tag(1, "ruby"));
    data.add(new Tag(2, "rails"));
    data.add(new Tag(3, "c / c++"));
    data.add(new Tag(4, ".net"));
    data.add(new Tag(5, "python"));
    data.add(new Tag(6, "java"));
    data.add(new Tag(7, "javascript"));
    data.add(new Tag(8, "jscript"));
    model.addAttribute("dropdown", data);
    return "dropDown";
}

second drop down code is

Map <\string, string> udata = null;
@RequestMapping(value = "ajaxAction0", method = RequestMethod.GET)
public @ResponseBody Map<String, String> findAllAgencies(
        @RequestParam(value = "ptype", required = true) String ptype) {
    udata = new HashMap<>();
    EntityManager em = entityManagerFactory.createEntityManager();
    em.getTransaction().begin();
    List<UserRecord> user = em
            .createNativeQuery("Select id, name, email from user_Record where id = :uid", UserRecord.class)
            .setParameter("uid", ptype).getResultList();
            for(UserRecord ur:user)     {
        udata.put(ur.getEmail(), ur.getName());
    }
    return udata;   }

hope it will help.

Solution 3:[3]

You can obtain a list of states based on the country:

@Autowired
StateService stateService;

@GetMapping("/states")
public @ResponseBody List<State> getStates(@RequestParam String country) {
    return stateService.getStates(country) ;
}

your State class will contain code and name;

$("select#country").change(function() {
    var countryVal = $("#country").val();
    $.ajax({
       url : '/states?country='+countryVal,
       method : 'GET',
    },
    success: function (states) {
        var stateSelect = $('#state'); // the state select element
        stateSelect.find('option').remove();
        for (i = 0; i < states.length; i++) { 
            stateSelect.append("<option value=" + states[i].code + " >" + states[i].name + "</option>")
        }
    },

    error :function()
    {
       alert("error");
    }          

});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Prade jo
Solution 3 Adina Rolea