How to populate dropdown list with JSON data as ajax response in jQuery

I am working on a j2ee application. In my application, I have a drop-down list (or a Select element). I want to populate this dropdown with JSON data as an Ajax response.

Below is the code I have:

Server-side code (json_source.java) that generates a JSON response .:

package demo.model; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.*; /** * Servlet implementation class json_source */ public class json_source extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JsonArray data_json=new JsonArray(); Statement st_loginId=null; ResultSet rs_loginId=null; try { Connection con=null; Class.forName("oracle.jdbc.OracleDriver"); /* Connection String for "OPERWH"(exadata) Database */ con=DriverManager.getConnection("jdbc:oracle:thin:*************","*****","*****"); con.setAutoCommit(true); st_loginId=con.createStatement(); rs_loginId=st_loginId.executeQuery("select login_id \"LOGIN ID\" from user_access"); //System.out.println("entered in frame_login_code"); int login_val=0; JsonObject json_response=new JsonObject(); while(rs_loginId.next()) { login_val++; JsonObject json=new JsonObject(); json.addProperty("value", "login"+login_val); json.addProperty("text", rs_loginId.getString(1)); data_json.add(json); } System.out.println(data_json); json_response.add("aaData", data_json); response.setContentType("application/Json"); response.getWriter().write(json_response.toString()); System.out.println(json_response); } catch(Exception ex) { System.out.println("Exception occured during retrieval of Login_Id in ComboBox :"+ex); ex.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } } 

and JSON data that was successfully generated using server-side code:

 { "aaData": [{ "value": "login1", "text": "kapils" }, { "value": "login2", "text": "davidn" }, { "value": "login3", "text": "alanp" }] } 

and below is the code of my client side (source1.jsp) that generate the ajax request:

(using $ .ajax ()):

 <script type="text/javascript"> $(document).ready(function() { $('#id_trial').click(function() { alert("entered in trial button code"); $.ajax({ type: "GET", url:"/demo_trial_application/json_source", dataType: "json", success: function (data) { $.each(data.aaData,function(i,data) { alert(data.value+":"+data.text); var div_data="<option value="+data.value+">"+data.text+"</option>"; alert(div_data); $(div_data).appendTo('#ch_user1'); }); } }); }); }); </script> <body> <div id="div_source1"> <select id="ch_user1" > <option value="select"></option> </select> </div> <input type="button" id="id_trial" name="btn_trial" value="Trial Button.."> </body> 

OR Usage ($ .getJSON ()):

 $.getJSON("/demo_trial_application/json_source", function (data) { $.each(data.aaData, function (i, data) { var div_data = "<option value=" + data.value + ">" + data.text + "</option>"; alert(div_data); $(div_data).appendTo('#ch_user1'); }); }); 

Now, when I clicked the button (#id_trial), the server-side code runs successfully and as a result, a JSON object is created. but I don’t get this “JSON response” in the success parameter callback function using jQuery ajax call.

, and besides the jQuery ajax call, I also tried using the $.getJSON function to get the JSON response .. but I did not get the JSON data.

So please tell me if there is any error in my code and how to get JSON data using the code above and fill in the drop down list.

I want to populate my dropdown with JSON data using ajax response. help me sort out this problem ... its very urgent for my application.

+6
source share
6 answers

try changing the jquery method variable, this can cause a problem (i.e. you use the data variable coming from the ajax callback, PLUS then try to assign it to the item object in the jquery method - changed to obj ):

  $.ajax({ type: "GET", url:"/demo_trial_application/json_source", dataType: "json", success: function (data) { $.each(data.aaData,function(i,obj) { alert(obj.value+":"+obj.text); var div_data="<option value="+obj.value+">"+obj.text+"</option>"; alert(div_data); $(div_data).appendTo('#ch_user1'); }); } }); }); 
+13
source

I use "for"

 var List; jQuery.ajax({ url: "/demo_trial_application/json_source", type: "POST", dataType: "json", async: false, success: function (data) { List = data.aaData $('#ch_user1').empty(); $('#ch_user1').append('<option value="">All</option>'); for (i in List ) { $('#ch_user1').append('<option value="' + List[i].value + '">' + List[i].text + '</option>'); } } }); 
+2
source
 <div class="col-lg-4"> <%--<input type="text" class="form-control" id="txtGender" />--%> <select class='form-control DropDown' id="txtGender"></select> </div> -------------------------------------------------------------------------------- $(document).ready(function () { $.ajax({ type: "POST", url: "AjaxCallGrid.asmx/GetDropDown", dataType: "json", contentType: "application/json; charset=utf-8", success: function (result) { $('.DropDown').empty(); $('.DropDown').append("<option value='0'>---Select---</option>"); $.each(result.d, function (key, value) { $('.DropDown').append($("<option></option>").val(value.iD).html(value.firstName)); }); } }); }); ------------------------------------------------------------------------- [WebMethod] public List<Students> GetDropDown() { DataTable dt = new DataTable(); List<Students> result = new List<Students>(); using (SqlConnection con = new SqlConnection(@"Data Source=DOS-PC\MARJI;Initial Catalog=examples;Integrated Security=True")) { using (SqlCommand cmd = new SqlCommand("select id,firstname from Students ", con)) { con.Open(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { result.Add(new Students { iD = Convert.ToInt32(dt.Rows[i]["id"].ToString()), firstName = dt.Rows[i]["firstname"].ToString() } ); } } return result; } } 
0
source

We can fill in the drop-down list as shown below. It is very easy for you, I think.

 var options = $("#options"); $.getJSON("/Country/GetAll/", function(response) { $.each(response, function() { options.append($("<option />").val(this.Id).text(this.Name)); }); }); 
0
source

Working with Laravel is my solution:

 $("#YOUR_DIV").on("change", function(){ var selected = $(this).val(); makeAjaxRequest(selected); }) function makeAjaxRequest(opts){ $.ajax({ type: "GET", url : '{{ action(' YOUR_CONTROLLER@YOUR _FUNCTION') }}', data: { opts: opts }, success: function(data) { NEW_JS_FUNCTION(data); } }); } function NEW_JS_FUNCTION(params) { $('#YOUR_DIV').empty(); $('#YOUR_DIV').append('<option value="">ALL</option>'); params.forEach(function(entry){ $('#YOUR_DIV').append('<option value="' + entry.KEY+ '">' + entry.TEXT + '</option>'); }); } 

It works. Hope this helps.

0
source

The easiest way is to download this library https://github.com/JocaPC/jquery-view-engine/tree/master/src . This jQuery library directly loads JSON in dropdows and looks perfect for your example. You just need to put the following code:

 success: function (data) { $('#ch_user1').view(data.aaData); } 

Take a look at this page https://jocapc.imtqy.com/jquery-view-engine/docs/ajax-dropdown for more details.

0
source

Source: https://habr.com/ru/post/957179/


All Articles