mstojanov
mstojanov

Reputation: 185

JSON not fetching success on codeigniter - [object Object]

What i'm trying to do here to populate second select from based from the first one with json format.

Everything goes okay i'm getting the results i need with exact num of rows from the model based on the ID which i send with the request but i have this error :

http://img546.imageshack.us/img546/8895/ng1g.png "error"

I'm trying to get the mark id based on the model selected which i have in database :

ID MARK_ID VALUE_MARK

Here is my jquery function :

$(document).ready(function(){
$("#mark").change(function() {
   var markId= $("#mark").val();
   if (markId!= "") {
     $.get(
    'upload/car_models?mark_id=' + markId,
    function(data){                     
        $.each(data, function(key, value){
               $("#model").append("<option value='" + key + "'>" + value + "</option>");
        })
    },
    "json"
);
   }
});
})

And in my controller i'm doing json encode like this for the variable which is back from the model

echo json_encode($models);

How can i fix this problem with object Object. Thanks. Any help will be appreciate. EDIT : Json structure :

[{"id":"50","mark_id":"50","value_mark":"Refine","value":"JAC"},     {"id":"50","mark_id":"50","value_mark":"Rein","value":"JAC"}]

Here is my json structure. id mark_id value_mark here have 2 rows returned from the model

Upvotes: 1

Views: 231

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115212

Try this,

$(document).ready(function(){
    $("#mark").change(function() {
        var markId= $("#mark").val();
        if (markId!= "") {
            $.get(
                'upload/car_models?mark_id=' + markId,
                function(data){   
                    var model=$("#model");
                    model.empty();
                    $.each(data, function(key, val){
                        model.append("<option value='" + val.value + "'>" + val.value_mark + "</option>");
                    });
                },
                "json"
                );
        }
    });
})

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

Your data is an array of objects. WHen you loop over that array with $.each key will be index, and value will be object at that index.

Try:

$.each(data, function(i, obj){
      $("#model").append("<option value='" + obj.value + "'>" + obj.value_mark + "</option>");
 });

I guessed at what properties you want to assign to <option> value and text

Upvotes: 1

Related Questions