2

Please bear with me as I am new to jQuery, and JEE and am not a programmer :-) I have followed a number of tutorials on how to dynamically populate a dropdown box; however I can not get it to work.

I want to select a State and populate the Region drop down based on that selection (each State is made up of Regions).

My issue is with the call to the java and return of values.

So far I have (mashed up from a number of tutorials) the following:

HTML

<div class="row">
            <div class="col-md-6">
                <div class="form-select-group">
                    <label for="selectState">Select State:</label>
                    <select class="form-control" id="selectState">
                        <option value="" disabled selected>Select your State</option>
                        <option>ACT</option>
                        <option>NSW</option>
                        <option>NT</option>
                        <option>QLD</option>
                        <option>SA</option>
                        <option>TAS</option>
                        <option>VIC</option>
                        <option>WA</option>
                    </select>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-select-group">
                    <label for="selectRegion">Select Region:</label>
                    <select class="form-control" id="selectRegion">
                        <option>Please select your State first</option>
                    </select>
                </div>
            </div>
        </div>

jQUERY

$(document).ready(function(){
$('#selectState').on('change', function() {
    //do something here
    //alert($("#accountName").val());

    $.ajax({
        type: "POST",
        url: "RegionView",
        cache: false,
        data: $(selectState).serialize(),
        success: function(data){
            $('#ajaxGetUserServletResponse').text(data);                
        }
    }).done(function(response) {
        // Clear options
        $("#selectRegion").find("option").remove();
        // Loop through JSON response
        $.each(response, function (index, value) {
            $('#selectRegion').append($('<option>', { value: value.name }, '</option>'));
        })
    });
});
});

JAVA

package client;

import java.io.IOException;

/**
* The purpose of this View is to return a list of Regions associated with a selected State.
*/

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import server.MySQLConnection;


@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

    response.getWriter().write("Here " + state);

    MySQLConnection.getConnection();

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

    if (listRegions == null || listRegions.isEmpty()) {
        response.getWriter().write("Please select a State");
    }else{
        response.getWriter().write("State found");
        request.setAttribute("selectRegion", listRegions);
    }
}
}
6
  • What is the data that you are getting inside the success callback of the ajax request? Commented Dec 26, 2017 at 5:30
  • "success: function(data){ $('#ajaxGetUserServletResponse').text(data); }" provides - "Here New South WalesState found". "}).done(function(response) { $('#ajaxGetUserServletResponse').text(response); $("#selectRegion").find("option").remove(); $.each(response, function (index, value) { $('#selectRegion').append($('<option>', { value: value.name }, '</option>')); })" does not display anything. Should I be using something else besides "$('#ajaxGetUserServletResponse').text(response);" to display the response? I tried "console.log(response);" and nothing appears in the log file. Commented Dec 26, 2017 at 11:27
  • You are mixing up two conventions. If you are using sucess callback inside the ajax request, you don't need to chain then function to the promise. Otherwise use then function and remove the success callback. One way or another you will be geeting the data in the response which you should be using next to append inside elements. Commented Dec 26, 2017 at 12:45
  • Thanks Ghosh. Unfortunately I don't understand what you just wrote. Are you able to give me some code please? Commented Dec 26, 2017 at 19:43
  • Hi Sandip, I am sure if this is what you meant; however I tried this and it did not work: "success: function(data){ $('#ajaxGetUserServletResponse').text(data); $("#selectRegion").find("option").remove(); $.each(response, function (index, value) { $('#selectRegion').append($('<option>', { value: value.name }, '</option>')); }) }" Commented Dec 26, 2017 at 22:40

1 Answer 1

0

This code answers my question as it allows me to dynamically populate a dropdown box with Jquery and Java:

Java:

@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("Please select a State");
}else{          
    String json = new Gson().toJson(listRegions);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}
}
}

JSON:

$(document).ready(function(){
$('#selectState').on('change', function() {
//do something here
//alert($("#accountName").val());

$.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();
    // Loop through JSON response
    $.each(responseJson, function(key, value) {
        $('<option>').val(key).text(value).appendTo($("#selectRegion"));
    });
});
});
});
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.