1

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

ahh. i m not doing JSONParse :(
No problem. I just wanted to know if you need further help. Have a nice day!
1

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...

Comments

0

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",
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.