Passing path to php returns undefined

- 1 answer

Ad

i am trying to pass a path to a php script and the script is supposed to then return all image files in that path in a array but all i keep getting is undefined error, can someone help please.

function LoadGallery(dir_path) {
  $.ajax({
    type: 'POST',
    url: "getimages.php",
    traditional: true,
    data:{ path : dir_path},
    type: "json",
    success: function(data){
        alert(data[0]);
    //    $("#image-container").val(data[0]);

    }
  });
}

PHP SCRIPT getimages:

<?php
if(isset($_POST['path'])){
    $dir = $_POST['path'];
    $img = array();

    if (is_dir($dir)) {
       if ($hnd = opendir($dir)) {
           while (false !== ($file = readdir($hnd))) {
               if ($file != "." && $file != "..") {
                    $img[] = $file;
                }
           }
           closedir($hnd);
        }
    }
    return $img;
 }
 ?>
Ad

Answer

Ad

change your php code to return json with result.

<?php
if(isset($_POST['path'])){
    $dir = $_POST['path'];
    $img = array();

    if (is_dir($dir)) {
       if ($hnd = opendir($dir)) {
           while (false !== ($file = readdir($hnd))) {
               if ($file != "." && $file != "..") {
                    $img[] = $file;
                }
           }
           closedir($hnd);
        }
    }
    echo json_encode($img);
 }
 ?>
Ad
source: stackoverflow.com
Ad