How to pass an array using PHP & Ajax to Javascript?

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

Leave a Comment