Jump to content

passing looped variables to a javascript when page created


turpentyne

Recommended Posts

dang! Another new one for me..

 

 

I had a javascript solution to view/hide div tags, but when I got the php loop set up the way I want, I realized, that it creates a problem with the div names.

I decided maybe I could automatically create a variable for to match each div that is created in the loop, but I'm not sure how to write those to the javascript?

 

Assuming I've got the right forum on this one.

 

Here's what I 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]))
    {
    document.getElementById(divs[i]).style.display='none';
    }
  }
onediv.style.display = 'block';
}

</script>

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

while($row = mysql_fetch_assoc($result))
{
    if($category != $row['component_category'])
    {
        $category = $row['component_category'];
        if(!$firstime){
               echo '</div><br><br>';
         }else{
            $firstime=true;
         }
        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>

\n";

}
?>



Link to comment
Share on other sites

If I understand you correctly, you want the result of this line:

$var{$row['comp_cat_name']} = "var_".$row['comp_cat_name'];

 

To be printed out in the JS, where the following bit of code is? If not, where do you get "$variable1" from?

var divs=[<?php echo "'".$variable1."'," and so on.... ?>];

 

Also, what exactly did you want to do with the first line of code? The "$var{}" bit doesn't make much sense, tbh. I suspect you might be a bit confused about the syntax here, possible mixing in the JS syntax..?

If so, remember that PHP and the JS is completely separate. For all that PHP cares (which it doesn't in regards to the JS function you posted) the JS is just pure text. Like everything else that's not PHP. After all, all of the PHP code is processed by the server, before the result is sent to the browser. Which, in turn, is responsible to parse all of the text as HTML, CSS, JS or whatever else it happens to be.

Link to comment
Share on other sites

Yeah, those are the two lines I'm thinking through. I just put $variable1 because I wouldn't know what the variables actually are. I know how to just echo a known variable into javascript, like html and any other. But if I don't know what that variable will be, then the whole idea fell apart. If I understand you right, I do want it to write this in at the same time all the rest of the html code is written from the server.

 

Maybe I should just write the javascript script inline on the divs I want to toggle on and off?

Link to comment
Share on other sites

You want to make every div on the page show / hide - able, right? Quite easy to do if you harness the power of the jay-Queries.

 

php loop

<div id='container'>
<?php

while( $row = $query ) {
echo '<div class="toggle" id="div' . $row['id'] . '">title 
    <p>some content</p>
</div>';
}

 

This will give your div's a unique ID for a different use within your scripts.  Which jQ you can map all the divs and apply a focused option. see this fiddle

 

Link to comment
Share on other sites

The best thing to do is to do all of the PHP parsing, before you send out anything to the browser. Do that, and you'll see that your problem is suddenly a very, very simple one.

 

BTW: I've fixed up your PHP part a bit, should give you some clues on how to write more maintainable code. ;)

<?php
// CF: Using sprintf () and templates makes things a whole lot easier to read.
$ExpandTemplate = <<<OutHTML
<div id="%1\$s" style="width:350px;padding-top:20px; class="select-toggler"
onclick="return showHide('%1\$s-expander');\"><img style="position:relative;top:-2px;"
src="images/structural/red-plus.gif" />%1\$s</div>
OutHTML;

$ExpandImageTemplate = <<<OutHTML
<div id="%1\$s-expander" style="float:left;padding-right:25px;display:none;" width="90">%2\$s <br><img src='%3\$s'></div>
OutHTML;

// and here's the loop I'm talking about.
$Output = '';
while ($row = mysql_fetch_assoc ($result)) {
if ($category != $row['component_category']) {
	$category = $row['component_category'];

	if (!$firstime) {
		$Output .= '</div><br><br>';
	} else {
		$firstime = true;
	}

	//CF: Changed output to be stored in a temp variable, as well as adding output escaping to prevent XSS etc.
	$Output .= sprintf ($ExpandTemplate, htmlspecialchars ($row['comp_cat_name']));

	// CF: Add the name of the JS variable to a comma-seperated list.
	$JSVariables = "var_" . htmlspecialchars ($row['comp_cat_name']). ", ";
}

//CF: Changed output to be stored in a temp variable, as well as adding output escaping to prevent XSS etc.
$Output .= sprintf ($ExpandImageTemplate, htmlspecialchars ($row['comp_cat_name']),
										htmlspecialchars ($row['component_name']),
										htmlspecialchars (rawurlencode ($row['image_filepath'])));

}

?>

 

The rest, however, I'll leave for you to figure out yourself. Best way to learn, now that you've gotten a tip on what you need to do.

 

Added:

Of course, using jQuery makes things quite a bit simpler as well. Especially if both methods are combined. No need to reinvent the wheel, after all. Unless it's for learning purposes. :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.