Harsha M V
Harsha M V

Reputation: 54949

jQuery Iterate through JSON Error

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:

enter image description here

Upvotes: 1

Views: 578

Answers (3)

Gdroid
Gdroid

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

dknaack
dknaack

Reputation: 60468

First create a jSON Object from your data string using jQuery.parseJSON. Then you can iterate with $.each.

Sample

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)
    });
}

JSFiddle Demo

References

Upvotes: 2

Darren
Darren

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);
});

JSFiddle Demo


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

Related Questions