Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return an array from php to ajax response in javascript

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

like image 913
fedrick Avatar asked Jul 21 '14 11:07

fedrick


2 Answers

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)
});
like image 199
Gautam3164 Avatar answered Oct 24 '22 07:10

Gautam3164


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);
    });
});
like image 1
t3chguy Avatar answered Oct 24 '22 08:10

t3chguy