2

This post is related to Dynamically populate a dropdown box with Jquery and Java

Which I have solved and posted the answer to. I now have another issue. This is my first project using json, java and html so a bit of a learning curve.

I use the same code to extract some lists (a list of Regions, a list of Districts); however, a different result/format is returned for the District list. The Region list is correct and returns:

enter image description here

Which I now successfully use to populate a drop down list. I then select one of the values and use very similar code to retune a list of Districts within the Region selected. This returns:

enter image description here

Note the square brackets and quotes.

The code I use is:

HTML:

            <div class="col-md-2">
                <div class="form-select-group">
                    <label for="selectRegion">Select Region:</label>
                    <select class="form-control" id="selectRegion" name="selectRegion">
                    <option value="" disabled selected>Select your State first</option>
                    </select>
                </div>
            </div>
            <div class="col-md-2">
                <div class="form-select-group">
                    <label for="selectDistrict">Select District:</label>
                    <select class="form-control" id="selectDistrict" name="selectDistrict">
                    <option value="" disabled selected>Select your State first</option>
                    </select>
                </div>
            </div>

JSON:

$(document).ready(function(){
$('#selectState').on('change', function() {
    $.ajax({
        type: "POST",
        url: "RegionView",
        cache: false,
        data: $(selectState).serialize(),
        success: function(data){
            $('#ajaxGetUserServletResponse').text(data);
        }
    }).done(function(responseJson) {
        dataType: "json",
        // Clear options
        $("#selectRegion").find("option").remove();
        $('#selectRegion').append($('<option value="" disabled selected>Select your Region</option>'));
        $("#selectDistrict").find("option").remove();
        $('#selectDistrict').append($('<option value="" disabled selected>Select your Region first</option>'));
        $("#selectGroup").find("option").remove();
        $("#selectSection").find("option").remove();
        $("#selectSubSection").find("option").remove();
        // Loop through JSON response to populate the Region drop down
        $.each(responseJson, function(key, value) {
            $('<option>').text(value).appendTo($("#selectRegion"));
        });
    });
});
    $('#selectRegion').on('change', function() {
        $.ajax({
            type: "POST",
            url: "DistrictView",
            cache: false,
            data: $(selectRegion).serialize(),
            success: function(data){
                $('#ajaxGetUserServletResponse').text(data);
            }
        }).done(function(responseJson2) {
            dataType: "json",
            // Clear options
            $("#selectDistrict").find("option").remove();
            $('#selectDistrict').append($('<option value="" disabled selected>Select your District</option>'));
            $("#selectGroup").find("option").remove();
            $('#selectGroup').append($('<option value="" disabled selected>Select your District first</option>'));
            $("#selectSection").find("option").remove();
            $("#selectSubSection").find("option").remove();
            // Loop through JSON response to populate the District drop down
            alert("Here1");
            $.each(responseJson2, function(key, value) {
                alert("Here2");
                $('<option>').text(value).appendTo($("#selectDistrict"));
            });
        });
    });

    $('#selectDistrict').on('change', function() {
        $.ajax({
            type: "POST",
            url: "GroupView",
            cache: false,
            data: $(selectDistrict).serialize(),
            success: function(data){
                $('#ajaxGetUserServletResponse').text(data);
            }
        }).done(function(responseJson) {
            dataType: "json",
            // Clear options
            $("#selectGroup").find("option").remove();
            $('#selectGroup').append($('<option value="" disabled selected>Select your Group</option>'));
            $("#selectSection").find("option").remove();
            $('#selectSection').append($('<option value="" disabled selected>Select your Group first</option>'));
            $("#selectSubSection").find("option").remove();
            // Loop through JSON response to populate the Group drop down
            $.each(responseJson, function(key, value) {
                $('<option>').text(value).appendTo($("#selectGroup"));
            });
        });
    });
  });

Java for Region (reads a selected State and returns a list of Regions which are populated into the drop down list):

    @WebServlet("/RegionView")
    public class RegionView extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String state = request.getParameter("selectState"); // From bootstrap

        MySQLConnection.getConnection();

        List<String> listRegions = MySQLConnection.listGroupRegions(state);

        if (listRegions == null || listRegions.isEmpty()) {
            response.getWriter().write("No Regions in this State.");
        }else{          
            String json = new Gson().toJson(listRegions);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json);
        }
    }
  }

I then select a Region and pass it to this java which returns a list of Districts. The Districts are found however the format returned is not correct and so the next drop down is not populated with this list:

    @WebServlet("/DistrictView")
    public class DistrictView extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String[] region = request.getParameterValues("selectRegion"); // From bootstrap
        String region0 = region[0];

        MySQLConnection.getConnection();

        List<String> listDistricts = MySQLConnection.listGroupDistricts(region0);

        if (listDistricts == null || listDistricts.isEmpty()) {
            response.getWriter().write("No Districts in this Region.");
        }else{
            String json = new Gson().toJson(listDistricts);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json);
        }
    }
 }

I want to return this list to the json and populate the drop down list so I can select a District and return a list of Groups in that District. However; even though I am converting to json it returns the value in square brackets and quotes.

3
  • This line is missing from your districts code response.setContentType("application/json"); Commented Jan 2, 2018 at 3:33
  • You are marvelous! Please set as answer and I will accept and vote up. Commented Jan 2, 2018 at 7:54
  • Glad to be of help! Commented Jan 2, 2018 at 9:14

1 Answer 1

2

This line is missing from your districts code response.setContentType("application/json");

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.