Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

This question already has an answer here:

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]
    ];
share|improve this question

marked as duplicate by Felix Kling, hakre, Sergio, Sindre Sorhus, davidkonrad Aug 17 '13 at 17:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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 8: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 8: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 8:19
    
Thats what I need to do .... and am not getting it how to achieve this – OM The Eternity Aug 17 '13 at 8:20
    
Then do it! Arrays in Javascript and PHP are not different. – Sven Aug 17 '13 at 8:20

4 Answers 4

up vote 6 down vote accepted

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.

share|improve this answer
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.

share|improve this answer

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
    }
});
share|improve this answer
    
Does not address the array transformation required. – rebroken Aug 17 '13 at 8:45
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)
    }
});
share|improve this answer
    
OP already json encoded the string in PHP. It's JavaScript that's the problem, and there's a simpler solution. – Madara Uchiha Aug 17 '13 at 8:33
    
His question suggests otherwise. The output is not JSON, it's the output of print_r or var_dump. – rebroken Aug 17 '13 at 8:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.