Reputation: 4223
So i have this piece of javascript, it posts to foo.php
with value val
, gets back data
, empties the container and call function graph
which will fill the container with a new chart.
$.post("foo.php", {val: val}, function(data){
if(data.length >0) {
$('#container').html('');
graph(data);
}
});
in foo.php
, how do I make it pass back an array instead of string? at the moment I just have an echo
in foo.php
that echos the data delimited by a comma, ie: 1,2,3,4,5
. then in the graph
function I have a split(',' data)
that creates an array for later use.
I mean, all this works fine, I'm just wondering if I can avoid the split step and have foo.php
return an array directly.
thanks!
Upvotes: 0
Views: 62
Reputation: 46900
json_encode your array in PHP and jquery can easily parse your JSON encoded data.
Upvotes: 3
Reputation: 220066
That's what json_encode
is for:
echo json_encode( $array );
Just remember to set JSON headers, so that jQuery will know to parse the returned data as JSON. If you don't, you'll have to specify that in your jQuery AJAX call as follows:
$.post("foo.php", {val: val}, function(data){
if (data.length > 0) {
$('#container').html('');
graph(data);
}
}, 'json'); // <-- Here you're specifying that it'll return JSON
Upvotes: 3