Hello,
I have a php function which passes a var to a javascript function and I don't understand why I keep getting an error that says the function is not defined. I though maybe there was a problem because the javascript function is in an iframe, but I tried putting it in the parent document and got the same result. Originally, I had this as a simple onclick=document.getElementById() within the echo statement to swap the img src attribute, which worked, but I needed to include image dimensions to dynamically adjust the width and height.
PHP code:
function get_project_img($subdir)
{
$dir = get_dir();
$imgdir = $dir . $subdir;
$files = scandir($imgdir);
foreach($files as $value) {
// check for image files
if(valid_image_file($value)) {
// if (!substr($value, 0, 1) == '.') {
// unset($files);
// build image array
$imgarr[] = $value;
}
}
$count = count($imgarr);
$rnd = rand(0, $count-1);
$rndimg = $imgarr[$rnd];
$imgid = str_replace("/", "img", $subdir);
for ($i=0; $i<$count; $i++) {
$size = getimagesize($imgdir . $imgarr[$i]);
list($width, $height) = $size;
$dimarr[$imgarr[$i]] = array("width" => $width, "height" => $height);
$imgname = rtrim($imgarr[$i], ".jpg");
echo '<a href="#" onclick="swap_attr('. $imgarr[$i] .')"><img class="floatleft" src="' . $imgdir . $imgarr[$i] . '" width="40" height="40" alt="thumb" /></a>';
}
echo '<img id="' . $imgid . '" name="' . $imgid . '" src="' . $imgdir . $imgarr[0] . '" width="' . $width . '" height="' . $height . '" alt="" />';
// var_dump($dimarr);
// return $dimarr;
}
JS code:
<script type="text/javascript" charset="utf-8">
<?
$pageurl = $_SERVER['PHP_SELF'];
if($pageurl == '/project.php') {
get_js_dimarr('after/');
get_js_imgarr('after/');
}
?>
function swap_atrr(image)
{
var imgname = image;
var rimgname = imgname.replace(".jpg", "");
var imgwidth = dimarr[imgname][1];
var imgheight = dimarr[imgname][2];
document.getElementById("afterimg").setAttribute("src", rimgname);
document.getElementById("afterimg").setAttribute("width", imgwidth);
document.getElementById("afterimg").setAttribute("height", imgheight);
}
</script>
Thanks for any help,
Jason