Sunday, 10 May 2015

populate dropdown using ajax in java

Populate Dropdown Using Ajax In Java

Here i have created some code which will bring the data using ajax from your controller of spring to your view and populate dropdown on the view.

Below is the controller method from where we are returning data to generate dropdown on view.  

Controller method

@RequestMapping(value="/getAddressList",method=RequestMethod.POST)
    public void getAddressList(Map<String, Object> map,HttpServletRequest request,HttpServletResponse response) throws IOException {
       
       
        List<WebAddress> addresses=new ArrayList<WebAddress>();
        for (Address add : addressService.listAddress()) {
                    WebAddress wadd=new WebAddress();
                    wadd.setId(add.getId());
                    wadd.setAddress1(add.getAddress1());
                    wadd.setAddress2(add.getAddress2());
                    wadd.setCity(add.getCity());
                    //wadd.setContacts(add.getContacts());
                    wadd.setState(add.getState());
                    wadd.setZip(add.getZip());
                    addresses.add(wadd);
        }
       
       
        Gson gson=new Gson();
   
       
        response.getWriter().write(gson.toJson(addresses));
    }



Now we are writing view and ajax call which will get the data and populate the dropdown on view.
for that we will create one select tag with ID let take dropdownID and then we will add options to this select box using jquery / javascript as Below

JSP view and page script
 

<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {


        $.ajax({
            type : "POST",
            dataType : 'json',
            url : "http://localhost:8080/getAddressList",
            success : function(data) {
                console.log(data);
                alert(data[0].address1);
                var options="<option value=''>--select country--</option>";
                $.each(data,function(k,v){
                    options +="<option value="+v.id+">"+v.address1 +","+v.address2+","+v.city+"</option>";
            
                    });         

                   $("dropdownID").html(options);
                }
        });
       
    });

</script>


<!--------your other html code -------->

<select id="dropdownID"></select>

<!--------your other html code -------->