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

1
  • use echo json_encode($arr_variable) this will convert your array into json format. Commented Jul 21, 2014 at 11:02

2 Answers 2

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)
});
Sign up to request clarification or add additional context in comments.

11 Comments

is that enough, how to display in javascript, can i write a normal each loop to display array values?
Param#2 Should be a bitmask or a depth, not a bool., changed since, but cannot change vote.
@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.
@gautam3164 You don't need the $.parseJSON as the $.post will automatically trigger that if it detects valid JSON syntax.
@t3chguy no.you have to parse it when you are processing a json data
|
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);
    });
});

2 Comments

can you please tell me how to display the array in javascript.. i need to display dynamically
Don't see the reason for the vote down but doesn't bother me overly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.