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.