tags:

views:

167

answers:

5

Hi All,

I want to write a function in javascript which will call the Getfilename.php and Get the $filesArray that is return in javascript.

GetFilenme.php is another file and I am trying to access this from Config.html

PHP : Getfilename.php

<?php
$dir = 'uploads/';

$dir = $_REQUEST['dir'] ;

$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file)
{
 if ($file!='.' && $file!='..' )
 {
  $filesArray[$Counter] = $file;
  echo $filesArray[$Counter].'<br>';
  $Counter = $Counter + 1;

 }
}
return $filesArray;
?>
A: 

Check this page http://ajaxpatterns.org/XMLHttpRequest_Call

The whole site is worth a look too.

rslite
+1  A: 

This is assuming you download and include the jQuery javascript library:

$(function() {
    $.get('getfilename.php', { dir : 'path/to/dir' }, function(data) {
        // you should now have a json encoded PHP array
        $.each(data, function(key, val) {
            alert('index ' + key + ' points to file ' + val);
        });
    }, 'json');
});

This should be your PHP (although very insecure):

<?php
$dir = $_REQUEST['dir'] ;

$filesArray = array(); 
$Counter = 0; 
$files = scandir($dir); 

foreach ($files as &$file) { 
    if ($file!='.' && $file!='..' ) { 
        $filesArray[$Counter] = $file; 
        echo $filesArray[$Counter].''; 
        $Counter++;
    }
} 

echo json_encode($filesArray); 
?>
cballou
A: 

At the end, do this:

print json_encode($filesArray);

and it will send back a json object, which Javascript can read easily.

mabwi
@cballou has provided a much more complete answer
mabwi
A: 

I am not using Ajax...

Using Pure Javascript

i want to write javascript function not using Jquery..........

NewBie
+1  A: 

If you're just using JavaScript, probably the simplest solution is to include that as a <script> tag.

eg:

<script src="Getfilename.php" type="text/javascript"></script>

Then in your PHP, instead of:

return $filesArray;

have it write some JavaScript.

echo "var result = ".json_encode($filesArray).";";

Your $filesArray value will now be in your javascript as the variable result.

<script>alert(result)</script>
bucabay