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