View Full Version : passing looped variables to a javascript when page created

07-29-2012, 04:43 AM
not sure if this is a javascript or php or ajax thing, but I'll post here.

I've been working on generating a looped result to the page, with category headers and results in a div that will open/close, when the category header is clicked on. Now that I've got the loop figured out, I realize it changes how I take care of the javascript for the div open/close.

I need to pass the generated div id's to the javascript when the page is created But I'm not sure how. I was thinking I'd autogenerate a php variable when I make the header, but I don't know where to go from there.

Here's what I've got:

<!-- here's the script I need to put the variables into -->
<SCRIPT LANGUAGE="JavaScript1.2">

function showHide(d)
var onediv = document.getElementById(d);
var divs=[<$php echo "'".$variable1."'," and so on.... ];
for (var i=0;i<divs.length;i++)
if (onediv != document.getElementById(divs[i]))
onediv.style.display = 'block';


// and here's the loop I'm talking about.

while($row = mysql_fetch_assoc($result))
if($category != $row['component_category'])
$category = $row['component_category'];
echo '</div><br><br>';
echo "

<div id=\"{$row['comp_cat_name']}\" style=\"width:350px;padding-top:20px;\">
<a class=\"select-toggler\" href=\"javascript:showHide('{$row['comp_cat_name']}-expander');\"> <img src=\"images/structural/red-plus.gif\" style=\"position:relative;top:-2px;\"/> {$row['comp_cat_name']}</a><br>\n";

// here's how I thought maybe I could create the variable. Seems to work fine. Just don't know how to get it to the javascript
$var{$row['comp_cat_name']} = "var_".$row['comp_cat_name'];

echo "<div id=\"{$row['comp_cat_name']}-expander\" style='float:left;padding-right:25px;display:none;' width='90'>{$row['component_name']} <br><img src='{$row['image_filepath']}'></div>



07-29-2012, 05:14 AM
I'm going to have to write a snippet about this question, there have been far too many people asking it, to answer it every time. Declare an array in javascript, have php 'push' the elements into the array, then use javascript to handle the elements any way you want. You can use a php loop to push the javascript array, just echo a push statement into the javacript. This way of doing it ensure that the loose 'typing' both javascript and php use doesn't cause problems with data types.