Populating one select menu based on another select menu using AJAX in Struts2

The same way you can do it in Struts2, but instead of servlet you can use the action. For example

@Action(value="/PopulateStateList", results=@Result(type="json", params = {"contentType", "application/json", "root", "map"}))
public class AjaxMapAction extends ActionSupport {

  Long countryId; //getter and setter

  Map<String, String> map=new HashMap<String, String>();

  public Map<String, String> getMap() {
    return map;
  }

    @Override
    public String execute() throws Exception {

        map.put("1", "India");
        map.put("2", "America");
        map.put("3", "England");
        map.put("4", "Japan");
        map.put("5", "Germany");

        return SUCCESS;
    }
}

Now, you can use the JSON on the client

  success: function(response)
  {
     if(typeof response==='object') 
     {
        var $select = $('#state');
        $select.find('option').remove();
        $('<option>').val("-1").text("Select").appendTo($select)
        $.each(response, function(key, value) {
        $('<option>').val(key).text(value).appendTo($select);
     }
  },

Leave a Comment