How can I get the filenames of a particular directory and populate it in an array?

Discussion in 'JavaScript' started by pedong, Jun 15, 2008.

  1. #1
    This is the sample code

    <script language=javascript>
    var width = 640;
    var height = 480;
    var imgAr1 = new Array();
    var rImg1 = new Array();

    //Assuming the content of the folder are 4 files
    imgAr1[0] = "photos2/snow.jpg";
    imgAr1[1] = "photos2/snow2.jpg";
    imgAr1[2] = "photos2/snow3.jpg";
    imgAr1[3] = "photos2/snow4.jpg";



    </script>
     
    pedong, Jun 15, 2008 IP
  2. crath

    crath Well-Known Member

    Messages:
    661
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    100
    #2
    this can be done with php, but i do not think it can be with js
     
    crath, Jun 15, 2008 IP
  3. pedong

    pedong Peon

    Messages:
    30
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    ok tnx.. i have a code in php getting the filenames of a directory my problem is how to pass to a javascript..

    $string="";
    $fileCount=0;
    $filePath=$PATH.'photosheader/'; # Specify the path you want to look in.
    $dir = opendir($filePath); # Open the path
    while ($file = readdir($dir)) {
    if (eregi("\.jpg",$file)) { # Look at only files with a .jpg extension
    $string .= "'$file'," ;
    $fileCount++;
    }
    }
     
    pedong, Jun 15, 2008 IP
  4. QiSoftware

    QiSoftware Well-Known Member

    Messages:
    805
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    158
    #4
    Yes, I think it can only be done with server side code. Javascript is used more on the client side [browsers]. JSP, AJAX, are other examples of server side languages which can provide information about directory structure.

    Q.
     
    QiSoftware, Jun 16, 2008 IP
  5. KatieK

    KatieK Active Member

    Messages:
    116
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    58
    #5
    If you've already got the filenames using PHP, you should be able to create a JavaScript array. Just echo the JavaScript defining the array out to the web page:

    
    <?php
      echo "<script type=\"text/javascript\">\n";
      echo "jsArray.push($phpArray[0]);\n";
      echo "jsArray.push($phpArray[1]);\n";
      echo "jsArray.push($phpArray[2]);\n";
      ...
      echo "</script>\n";
    ?>
    
    Code (markup):
    Let me know if that works.
     
    KatieK, Jun 16, 2008 IP