Apologies if this explanation isn\'t clear, it\'s hard for me to understand too. How can I use PHP & Ajax to send an array to Javascript? I\'m using Aja
Try:
$.ajax({
url: "<?php echo site_url('demo/getPhotos/'); ?>",
type: 'POST',
data: form_data,
dataType:"json",
success: function(data) {
alert(data[0]);
}
On the PHP side, you'll be wanting to print:
print json_encode($photos);
Another thing you might try in order to better encapsulate your code, and as an example of further JSON gooodness, would be:
print json_encode(array("photolist"=>$photos,"photo_owner"=>"Me!"));
Then on the server, you'd access these with:
data.photolist[0]; //First photo
data.photo_owner; //The owner of the photo set
json_encode
is definitely the way to go. jQuery even has built-in support for parsing JSON. You could use e.g.
$.ajax({
url: "<?php echo site_url('demo/getPhotos/'); ?>",
type: 'POST',
data: form_data,
dataType: 'json', // will automatically convert array to JavaScript
success: function(array) {
alert(array[0]); // alerts first string
}
});
I made an array $result
in PHP and at the end of request.
echo json_encode($result);
and in JS $.post
handler function :
var obj = $.parseJSON(data);
var v = data.k;
where k
is key value in associative array.
json_encode rulez when you need this stuff.
I recently learned this cool thing too! Here's how you do it:
function jsonResponse($array) {
header('Content-type: application/json; charset=utf-8;');
die(json_encode($array));
}
This is optional, if you want to do it, you don't have to, but in my MVC system, I tend to write this way... So first I make an ajax request (prototype), to a script, that later calls this function jsonResponse I mentioned earlier...
new Ajax.Request('URL',
{
method:'post',
onSuccess: function(transport){
res = transport.responseJSON;
$('actionInformation').update(res.username);
},
onFailure: function(){
alert('Something went wrong...')
}
});
This is the jscript code, notice the res.msg, this is where we can operate with array. But, be sure to send response in JSON format in your PHP, using the jsonResponse function, it's easy to use, e.g., your php function can look something like this :
function ajax_get_user() {
$userName = 'Adrian';
$active = 1;
jsonResponse(array('username' => $username, 'active' = $active));
}
Later you can get it easy, res.username, res.active.
I think this should do it!
return the json itself and then construct the array in js by looping over the json as follows:
var array=[];
for(var key in json)
{
if(json.hasOwnProperty(key))
array.push(json[key]);
}
Or you can simply work with the json itself any reason for needing the array?
something like json[0] or json[1] etc.