3

Okay, So I have the countries and their respective cities in a database table. And two dropdowns country and city. The options for cities will appear after user selects a country.

I am using AJAX for recieving cities based on country selected.

Here is the code:

 $(function(){

             $('#aicount').on( 'change', function () {        //#aicount: Contry dropdown , #aicity:City dropdown
                 var e= document.getElementById("aicount");

                    $.ajax( {
                          url: 'ReturnCity',                 // URL of Servlet
                         method:'post',
                          data:
                          {
                             country: e.options[e.selectedIndex].text

                           },     // parameters to Servlet
                          dataType: 'json',            

                          success: function ( res ) {

                                   //Don't know what to do here.

                          }
                       });
             });

         });

I am sending the selected country to a servlet which return the cities. The servlet code is:

String country=request.getParameter("country");
        JSONObject json=new JSONObject();
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db",user,pass);
            PreparedStatement ps=con.prepareStatement("select Name from city where countc=(select cid from country where name=?);");
            ps.setString(1, country);
            ResultSet rs=ps.executeQuery();
            while(rs.next())
            {
                json.put(rs.getString("Name"),"city");   // Not sure about this part
            }
            response.setContentType("application/json");
            response.getWriter().write(json.toString());
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

How do I do the rest of the part?

I am just learning to use JSON and AJAX.

user63762453
  • 1,734
  • 2
  • 22
  • 44

1 Answers1

2

Okay, so in the success function you need to append the option tags here:

success: function (res) {
  res = JSON.parse(res);
  $.each(res, function (idx, val) {
    $("select").append('<option value="' + idx + '">' + val + '</option>');
  });
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252