0

I have Codeigniter application which fetches data from database as result array, converts data to Json and displays the results. However I keep getting undefined as display result.

Model

 $this->db->where('product_name',$sid);
      //  $this->db->select('product_title');
        $res = $this->db->get('products');
         $data = $res->result_array();  
         return $data;

View:

<script language="javascript">
    $('#findsubmit').click(function() {
        $.get("/products/index.php/find/lookup",{id : $('#id').val() },function(data) {

            $('#result').html('Product name: ' + data.product_name);
            //+ ' Last name: ' + data.lastname);
        },"json");
        return false;
});
</script>

Resulting array I receive in Firebug:

[{"category":"camera","product_name":"Sony HX20"},{"category":"camera","product_name":"Canon SZ220"}]

If I create simple array like this all works fine:

return array('category' => 'camera','product_name' => 'Sony HX20');

Resulting array I receive in Firebug:

{"category":"camera","product_name":"Sony HX20"}

1 Answer 1

1

In your JSON data, you receive an array of several results: data.product_name is not defined, but data[0].product_name and data[1].production_name are.

You should try to either return only one result (like the one you build manually), or iterate on data.

Edit: here's a sample on how to use $.each:

var names = 'Product name: ';
$.each(data, function(index, element) {
    if (index > 0) {names += '; ';}
    names += element.product_name;
});
$('#result').html(names);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks now it works. Any suggestion on how to iterate on data? Just use for loop?
You can use a loop or the jQuery function $.each
Thank you. Any idea how to add it to my code as I am quite new to Jquery.

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.