Page 1 of 1

getting the values of a php array into a javascript array.

Posted: Wed Jan 12, 2005 6:08 pm
by sos
this is what I am trying to do I am trying to get all the pictures in a directory and feed them into a php array then I want to take that array and feed it to a javascript array so I can use them with javascript

any body now how I can do this or if this can be done

like i want to use them for an image gallery that I am trying make. its going to use OnmouseOver and OnmouseOut events I need a way to get all the files in the directory thats where php comes in then I want to use javascript to reference them on the page.

Posted: Wed Jan 12, 2005 6:47 pm
by feyd
directory contents has been talked about very recently; search for "opendir", under my name.

As for tossing them to Javascript, that's a simple matter of writing out all the elements into a Javascript array.

Posted: Wed Jan 12, 2005 7:11 pm
by printf
Hi


Here is a simple example, (function)

Code: Select all

<?

function get_list ( $path, $ok )
&#123;
	$files = array ();

	if ( $dir = opendir ( $path ) )
	&#123;
		while ( ( $file = readdir ( $dir ) ) !== false )
		&#123;
			if ( $file != '.' && $file != '..' && is_file ( $path . '/' . $file ) && in_array ( substr ( $file, ( strrpos ( $file, '.' ) + 1 ) ), $ok ) )
			&#123;
				$files&#1111;] = $file;
			&#125;
		&#125;

		closedir ( $dir );
	&#125;

	return ( $files );
&#125;

// the array of file types to return

$ext = array ( 'gif', 'jpg', 'jpeg', 'bmp', 'png', 'tif' );

// the directory to read, no trailing -> '/'

$dir = '/path_to_directory/read';

// usage

$out = get_list ( $dir, $ext );

if ( empty ( $out ) )
&#123;
	echo 'No files match allowed types found';
	exit ();
&#125;
else
&#123;
	$javasript_array = "'" . implode ( "', '", $out ) . "'";
&#125;


// then on your output page header, inside of PHP (example)

echo "var img = new Array(" . $javasript_array . ");";


?>

printf