Nishan Singha Nishan Singha - 1 month ago 9
JSON Question

Extract json data from ajax response (solved)

Here is my js function

<script>
function get_class_group(class_id) {

$.ajax({
url: '<?php echo base_url();?>index.php?admin/get_class_group/' + class_id ,
success: function(response)
{
var obj = response;
alert(obj);
}
});

}
</script>


This gives me output like

[{"section_id":"13","name":"A","nick_name":"A","class_id":"13","group_id":"4","teacher_id":"6","id":"4","group_name":"Science"}]
[{"section_id":"13","name":"A","nick_name":"A","class_id":"13","group_id":"4","teacher_id":"6","id":"4","group_name":"Science"},
{"section_id":"22","name":"B","nick_name":"b","class_id":"13","group_id":"4","teacher_id":"0","id":"4","group_name":"Science"}]


If i write
alert(obj.section_id);
it gives me


error:"undefined".


How can i get a specific value from this json?

Here is my backend function:

function get_class_group($class_id)
{
$this->db->select('section.*, class_group.*');
$this->db->from('section');
$this->db->join('class_group', 'section.group_id = class_group.id', 'left');
$this->db->where('section.class_id', $class_id);
$groups = $this->db->get()->result_array();

foreach ($groups as $row) {
$value[] = $row;
echo json_encode($value);
}
}

Answer

Use a each loop, your response is a array of objects,use stringify to turn the string in a object

$.ajax({
   url: '<?php echo base_url();?>index.php?admin/get_class_group/' + class_id ,
   success: function(response) {
     response = JSON.stringify(response);
     $.each(response,function(i,v){
       console.log(v.section_id);
     });
   }
});

place the echo outside the foreach function

foreach ($groups as $row) {
            $value[] = $row;

        }
header('Content-Type: application/json');//add the json header if you want to remove the js stringify function 
echo json_encode($value);
Comments