8

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]
    ];
OM The Eternity
  • 15,694
  • 44
  • 120
  • 182
  • 1
    Why don't you already encode the data in that format on the server side? If you want to parse the JSON, use `JSON.parse` or set the `dataType: 'json'` option in your `$.ajax` call or set the right response headers in PHP. – Felix Kling Aug 17 '13 at 08:14
  • I do the same, in php code i did json_encode(myarray) and echoed it... Not i want this to be converted to Javascript required dimensional array.... – OM The Eternity Aug 17 '13 at 08:16
  • But the format of the array in PHP is different than the one you want in JavaScript. So that's why I'm asking, why don't you create the data in the right format on the server side? – Felix Kling Aug 17 '13 at 08:19
  • Thats what I need to do .... and am not getting it how to achieve this – OM The Eternity Aug 17 '13 at 08:20
  • Then do it! Arrays in Javascript and PHP are not different. – Sven Aug 17 '13 at 08:20
  • You may want to clarify that you've already encoded it into JSON in PHP, please post your correct output after `json_encode`ing. – Madara's Ghost Aug 17 '13 at 08:25
  • Output is claimed to be JSON but I see no evidence of that. – rebroken Aug 17 '13 at 08:38
  • @rebroken Find the proof above..... – OM The Eternity Aug 17 '13 at 08:40
  • Ok. So the correct strategy has been outlined multiple times. If you are looking for a line-perfect copy and paste solution then it would be clearer if you posted the actual JSON you are returning rather than the call to json_encode, because by that point it's a Javascript exercise and not a PHP one. – rebroken Aug 17 '13 at 08:43
  • @rebroken Ouput of json_encode also updated above... – OM The Eternity Aug 17 '13 at 08:47
  • It might help to do `header('Content-Type: application/json');` before outputting the JSON. – Ja͢ck Aug 17 '13 at 09:56
  • Hii...I have same problem my array is not convert into json format in yii2 and I have to converted array send to ajax... – Priyanka Ahire Apr 09 '16 at 03:48
  • Please help me how to do I have attach link of my stack overflow question http://stackoverflow.com/questions/36469759/unable-to-render-data-to-different-view-page-in-yii2/36472092?noredirect=1#comment60565534_36472092 – Priyanka Ahire Apr 09 '16 at 03:48

4 Answers4

11

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.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
4
http://api.jquery.com/jQuery.getJSON/

$.getJSON('ajaxfetch.php', function(data) {
  var locations = []; 

  $.each(data, function(key, val) {
    locations[val.deviceID] = [];
    locations[val.deviceID].push(val.id);
    locations[val.deviceID].push(val.latitude);
    locations[val.deviceID].push(val.longitude);
  });
});

Not 100% tested but it's along the right lines. Unsure where you get the location name from as it's not in the array so I used deviceID. Using getJSON should make your life easier.

Fabor
  • 567
  • 9
  • 21
0

Make sure your output is valid JSON, then specify the dataType: "json" in your jQuery AJAX request:

$.ajax({
    type: "POST",
    url: "ajaxfetch.php",
    dataType: "json",
    success: function (result) {
        console.log(result); //Now a JSON object
    }
});
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
-1
var locations = [];
$.ajax({
    type: "POST",
    url: "ajaxfetch.php",
    dataType: "json",
    success: function (result) {
       result.forEach(function(loc) { locations.push(new Array(loc.deviceID, loc.latitude, loc.longitude, loc.id)) });
       // locations is now in desired format (except non-existent place name)
    }
});
rebroken
  • 603
  • 4
  • 9