Reputation: 54949
i have JSON data as follows
{"4":"Bangles","2":"Rings"}
I am trying to Iterate through the content to populate the Dropdown
$("#ProductProductTypeId").change(function(){
var product_type_id = $(this).val();
console.log(product_type_id);
$.ajax({
type: "get",
url: "/alankruti/admin/product_categories/get_category/"+product_type_id,
//data: country_id,
success:function(data){
console.log(data);
var options = '';
$.each(data, function (key,value) {
console.log(key);
console.log(value);
options += '<option value="'+key+'">'+value+'</option>';
console.log(key + " " +value)
});
}
});
});
Error:
Upvotes: 1
Views: 578
Reputation: 86
Agree with answer by dknaack. Alternatively, try setting dataType: "json" in ajax. This ensures that in successHandler, the data object is a json object.
$.ajax({
type: "get",
dataType : "json",
...
Upvotes: 0
Reputation: 60468
First create a jSON Object from your data string using jQuery.parseJSON
. Then you can iterate with $.each
.
success:function(data){
// create json object from data (string)
jsonObj = jQuery.parseJSON( data);
console.log(data);
var options = '';
// iterate through json
$.each(jsonObj , function (key,value) {
console.log(key);
console.log(value);
options += '<option value="'+key+'">'+value+'</option>';
console.log(key + " " +value)
});
}
Upvotes: 2
Reputation: 13128
Taking your json:
{"4":"Bangles","2":"Rings"}
A simple each()
loop like this works:
$.each(items, function(k, values) {
console.log(k);
console.log(values);
});
Simply meaning all you had to do is
var options;
$.each(items, function(k, values) {
options += "<option value='" + k + "'>" + values + "</option>";
});
// then append options to select...
Upvotes: 1