16

In my application I have a drop-down list. I want to populate this drop-down list with JSON data from an Ajax response.

Below is the code what I have:

The JSON data which the server sends:

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

and Below is my Client side code which generates 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 Using ($.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 on button (#id_trial), the server side code executes successfully and as a result JSON object created But I am not getting that "JSON response" in callback function of Success parameter using jQuery's ajax call.

I also tried with $.getJSON function to receive JSON response..but I didn't get JSON data.

So please tell me if there is any mistake in my code, and how to get JSON data using above code and populate drop-down list.

miken32
  • 42,008
  • 16
  • 111
  • 154
kits
  • 191
  • 1
  • 2
  • 9

7 Answers7

26

try to change the jquery method variable, it might be causing the problem (i.e., you are using the data variable coming from the ajax callback PLUS are then trying 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'); 
                });  
                }
          });
        });
jim tollan
  • 22,305
  • 4
  • 49
  • 63
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
  • Jim, In that case I have tried the kits code and it is working fine, the only change is, I have used PHP server side code to generate the json objects. Is it give much difference in place? can you please guide me on this? – Krish R Nov 01 '13 at 11:43
  • I highly recommend console.log() over alert(). – unqualified Jan 29 '23 at 02:14
3

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

Working with Laravel this 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 can help.

1

We can populate dropdown like below . it's very easy for you all i guess.

var options = $("#options");
    $.getJSON("/Country/GetAll/", function(response) {
         $.each(response, function() {
         options.append($("<option />").val(this.Id).text(this.Name));
     });
  });
dush88c
  • 1,918
  • 1
  • 27
  • 34
-1
<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;
                }
            }
-1

Try as follows

<select id="xxx"></select>

success: function (response) {                   

     for (var i = 0; i < response.length; i++) {

           $("#xxx").append("<option value='" + response[i]["id"] + "'>" + response[i]["name"] + "</option>");

     }

}
Nisal Edu
  • 7,237
  • 4
  • 28
  • 34
-1

This is how you can do it:

$(".ddEvent").on('change', function(e){
    const selectedEvent                 = $(this).val();
    $("#ddExhibitor").empty();
    $("#ddExhibitor").append("<option value='-1'>-- Choose Exhibitor --</option>");

     $.ajax({
         url: '/dashboard/get-exhibitors/'+selectedEvent,
         type: 'GET',
         success: function success(data) {
         if(data.exhibitors.length > 0){
             data.exhibitors.forEach(exhibitor => {
                  $("#ddExhibitor").append("<option value='" + exhibitor.id + "'>" + exhibitor.exhibitor_name + "</option>");
                            });
                        }
                    },
                    error: function error(err) {
                        alert(data.error);
                    }
                });
            });
hackernewbie
  • 1,606
  • 20
  • 13