5

how to return an array in php to ajax call,

ajax call :

$.post('get.php',function(data){
alert(data)

});

get.php

$arr_variable = array('033','23454')
echo  $arr_variable;

in the alert(data), it is displaying as Array (i.e only text), when i display data[0], 1st letter of Array i.e A is displaying.

Any suggestions ? where i have done wrong

fedrick
  • 341
  • 2
  • 5
  • 21

2 Answers2

13

Use to encode the array like

$data['result'] = $arr_variable;
echo json_encode($data);
exit;

And in the success function try to get it like parseJSON like

$.post('get.php',function(data){
    var res = $.parseJSON(data);
    alert(res.result)
});
GautamD31
  • 28,552
  • 10
  • 64
  • 85
  • is that enough, how to display in javascript, can i write a normal each loop to display array values? – fedrick Jul 21 '14 at 11:03
  • Param#2 Should be a bitmask or a depth, not a bool., changed since, but cannot change vote. – t3chguy Jul 21 '14 at 11:04
  • @prassu I have updated my answer to be compatible with a dynamic amount of elements in the PHP array, after transmission it will alert each one, one by one. – t3chguy Jul 21 '14 at 11:08
  • @gautam3164 You don't need the $.parseJSON as the $.post will automatically trigger that if it detects valid JSON syntax. – t3chguy Jul 21 '14 at 11:10
  • @t3chguy no.you have to parse it when you are processing a json data – GautamD31 Jul 21 '14 at 11:11
  • No you do not, if the dataType, which by default is auto, is set to JSON it will automatically parse it into a Javascript Array-Like Object. – t3chguy Jul 21 '14 at 11:11
  • Sometimes it is not triggered due to the JSON Syntax being incorrect or the response headers being malformed. – t3chguy Jul 21 '14 at 11:12
  • The dataType is not POST. The TYPE is Post. Read the doc before stating the wrong. http://api.jquery.com/jquery.post/ `dataType Type: String The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).` – t3chguy Jul 21 '14 at 11:15
  • ok cool...data is posted but data type will need to parse right.?so either you have to use $.postJSON() or in the success you have to use `parseJSON` – GautamD31 Jul 21 '14 at 11:17
  • http://stackoverflow.com/questions/5289078/parse-json-from-jquery-ajax-success-data – GautamD31 Jul 21 '14 at 11:20
  • I think you can refer these..In fact we use parsing since the data will be returned in an normal format..like a json encoded string..you have to parse it. – GautamD31 Jul 21 '14 at 11:21
1

instead of echo $arr_variable; use echo json_encode($arr_variable); and then in jQuery you can access it like an object.

Once it is an object, you can access it as data[0] and so forth.

$.post('get.php',function(data){
    $.each(data, function(d, v){
        alert(v);
    });
});
t3chguy
  • 1,018
  • 7
  • 17