ajax + servlet country state city list

I am trying to populate city, country and statelist using ajax, and servlets. Now I know how to get the XMLhttpRequest object. There is a standard mechanism to do that and depending on the cross browser compatibility, you do get a ActiveX or a xml object..

Then you send a request to the actionservlet, using xmlhttprequest.open() and you send the request and you have an event handler function to take care of onreadystatechange issue, Now, when it comes to receiving the response, I get an error stating that the response is not completely received, i.e the status != 4... now.

I was wondering, how does the entire mechanism work..

how to put the parameters in the request, send it to servlet, and then I know how to retreieve the param from the URL.. but then how to send a valid response...??

I am confused on the ajax part, because I am not using / not use PHP. It is harder to think. Please suggest what should be done.

Is there any easier way to populate a city, country and state list??



Just let the servlet return the desired dropdown options in the desired format based on the request parameters in the doGet() method. Here's an example which returns it in JSON format with help of Google Gson:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String type = request.getParameter("type"); // Returns "country" or "state".
    String value = request.getParameter("value"); // Value of selected country or state.
    Map<String, String> options = optionDAO.find(type, id); // Do your thing to obtain them from DB. Map key is option value and map value is option label.
    String json = new Gson().toJson(options); // Convert Java object to JSON string.

    response.setContentType("application/json"); // Inform client that you're returning JSON.
    response.setCharacterEncoding("UTF-8"); // Important if you want world domination.
    response.getWriter().write(json); // Write JSON string to response.

Assuming that the above servlet is mapped on an url-pattern of /options, you could use it as in the following JSP example with help of jQuery. I am recommending jQuery because you would otherwise end up with 10 times as much JavaScript code needed for this "simple" task.

<%@ page pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
        <title>SO question 3983929</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
            $(document).ready(function() {
                $('#country').change(function() { fillOptions('state'); });
                $('#state').change(function() { fillOptions('city'); });
            function fillOptions(dropdownId) {
                var dropdown = $('#' + dropdownId);
                $.getJSON('options?type=' + dropdownId + '&value=' + $(this).val(), function(opts) {
                    $('>option', dropdown).remove(); // Clean old options first.
                    if (opts) {
                        $.each(opts, function(key, value) {
                    } else {
                        dropdown.append($('<option/>').text('Please select ' + dropdownId));
            <select id="country" name="country">
                <c:forEach items="${countries}" var="country">
                    <option value="${country.key}" ${param.country == option.key ? 'selected' : ''}>${country.value}</option>
            <select id="state" name="state">
                <option>Please select country</option>
            <select id="city" name="city">
                <option>Please select state</option>

Here I am assuming that you've already prepopulated the ${countries} as being a Map<String, String> in a servlet which has preprocessed the request to this JSP for the initial display.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.