I have this result
{"policy":[{"id":"1","policy_name":"Policy 1","description":"Testing","status":"Active","valid_until":"2022-05-18","tags":"Test","active":"0","date_added":"2022-05-18 05:36:02"}]}
And I want to display the policy_name
from the array and I’ve tried to alert it using this alert(response['policy'].policy_name);
but I have an error.
43:4801 Uncaught TypeError: Cannot read properties of undefined (reading 'policy_name')
Updated
This is my whole code:
AJAX
$("*[id^='pol_action']").each(function() {
$(this).change(function(){
var value = $(this).val();
var id = $('option:selected', this).attr('r-id');
if($(this).val() == 'edit')
{
$.ajax({
url: "<?php echo base_url();?>admin/leads/getPolData",
type: "POST",
data: {id: id},
success: function(response){
$('#update_policy_modal').modal('show');
alert(response['policy'].policy_name);
console.log(response);
},
error: function(data){
console.log('error');
}
});
}
else if ($(this).val() == 'delete')
{
}
});
});
Controller
public function getPolData()
{
$id = $this->input->post('id');
$policy = $this->leads_model->getDataPol($id);
$this->page_data['policy'] = $policy;
echo json_encode($this->page_data);
}
Model
public function getDataPol($id)
{
$where = array(
'id' => $id,
);
$this->db->select('*');
$this->db->from('tblpolicies');
$this->db->where($where);
$query = $this->db->get();
return $query->result();
}
What can I try to resolve this?
3
Answers
In your Ajax call, try json parsing and then alert the field:
I edited the answer, the below was for Javascript:
You are accessing an array so it should be:
You can try adding dataType: "JSON" so you don’t have to parse JSON, like below. Then you can try to loop through the array of data: