Reputation: 101
I really don't know how to transform array in object.
what I need is my array could transform into like this object :
var locations= [
{lat: -22.9, lng: -43.23},
{lat: 23.03, lng: 113.12},
{lat: 23.12, lng: 113.25},
{lat: -7.24917, lng: 112.75083},
{lat: -6.323116, lng: 106.870941},
{lat: 40.69, lng: -73.99},
{lat: 40.74, lng: -73.94}
];
I retrieve the data with ajax :
$(function() {
$.ajax({
url : '<?= base_url('admin/getCustomerLatLong'); ?>',
method : 'GET',
// dataType : 'JSON',
success : function(data) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error while getting the data. Call the developer!');
}
});
});
and I am using codeigniter, here is getCustomerLatLong
function in my controller:
public function getCustomerLatLong() {
$data = $this->M_customer->getAllCustomers()->result();
$locations = array();
foreach ($data as $location) :
$locations['lat'] = $location->latKota;
$locations['lng'] = $location->lngKota;
echo json_encode($locations);
endforeach;
}
please any answer would be helpful for me, thanks in advance.
Upvotes: 0
Views: 42
Reputation: 35180
I would imagine you issue is down to the fact that you're using echo
inside your loop.
Try changing your controller to something like:
public function getCustomerLatLong()
{
$data = $this->M_customer->getAllCustomers()->result();
$locations = [];
foreach ($data as $location) {
$locations[] = [
'lat' => $location->latKota,
'lng' => $location->lngKota,
];
}
echo json_encode($locations);
}
You might also need to uncomment dataType : 'JSON',
Hope this helps!
Upvotes: 3