I am fetching a JSON encoded array using AJAX from a PHP file, but in JavaScript I need to use it as an array, how can I create an array in Javascript?
My AJAX call to PHP File:
$.ajax({
type:"POST",
url:"ajaxfetch.php",
success:function(result){
alert(result);
}
});
ARRAY Created in PHP File :
Array
(
[0] => Array
(
[id] => 4
[deviceID] => xyz123
[latitude] => -33.80010128657071
[longitude] => 151.28747820854187
[altitude] => 34.78788787
[createdDate] => 2013-08-15 23:00:00
[delete] => 0
)
[1] => Array
(
[id] => 5
[deviceID] => jdkfhjskh344
[latitude] => -33.950198
[longitude] => 151.259302
[altitude] => 76.44455
[createdDate] => 2013-08-15 21:50:42
[delete] => 0
)
[2] => Array
(
[id] => 1
[deviceID] => abc223
[latitude] => -33.890542
[longitude] => 151.274856
[altitude] => 21.4454455
[createdDate] => 2013-08-15 20:00:00
[delete] => 0
)
)
I json encoded this array in PHP but AJAX retrieved it and is outputted in a string.
ABOVE ARRAY json encode as given below:
$data = array();
$data = $locate_obj->getAllDeviceLocation();
echo json_encode($data);
Output of json_encode
[{"id":"4","deviceID":"xyz123","latitude":" -33.80010128657071","longitude":"151.28747820854187","altitude":"34.78788787","createdDate":"2013-08-15 23:00:00","delete":"0"},{"id":"5","deviceID":"jdkfhjskh344","latitude":"-33.950198","longitude":"151.259302","altitude":"76.44455","createdDate":"2013-08-15 21:50:42","delete":"0"},{"id":"1","deviceID":"abc223","latitude":"-33.890542","longitude":"151.274856","altitude":"21.4454455","createdDate":"2013-08-15 20:00:00","delete":"0"}]
I'm looking for the way I can create an array in Javascript with the output I recieve in ajax response, so that I can come up with an array of format:
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
Answer
There are three solution to this problem:
If you want to modify the structure on the client side, have a look at Access / process (nested) objects, arrays or JSON.
No comments:
Post a Comment