Page 1 of 1

how do I pass a php variable to javascript

Posted: Fri Oct 31, 2008 10:04 am
by Darkmatter5
I have a page that has this Javascript at the top.

Code: Select all

 
<script type="text/javascript">
<!--
var imageURL="images/blank_graph.png";
 
if(document.images) {
    var graph=new Image();
    graph.src="images/graphs/152008.png";
    
    var blank=new Image();
    blank.src="images/blank_graph.png";
}
function changeImage() {
    if(document.images) {
        if(imageURL=="images/blank_graph.png") imageURL="images/graphs/152008.png";
        
        document.graph.src=imageURL;
    }
}
//-->
</script>
 
And down in the page is PHP that produces this code:

Code: Select all

echo "<a onClick='changeImage()'> $row2[year]</a>";
Now as you can see the intent is for this link to change an image to another image if clicked. But I need to send the dynamic filename to the Javascript. How can I do this?

Here is the code for the image that will be changed.

Code: Select all

<img src="images/blank_graph.png" name="graph">
BTW here's where I got the code for the Javascript:
http://www.sislands.com/coin70/week3/onclick.htm

Now for my question. I have a php variable that's created just before the code that creates the onClick event, that contains the location and filename of the file associated with the year. I need to pass this "$filename" php variable to the Javascript and use it at lines 8 and 15. Where the text "images/graphs/152008.png" is, is where the dynamic variable needs to be used at. How can I do this? Basically the year link needs to run the changeImage javascript function with the specific filename as an argument and then run the javascript with that variable.

Re: how do I pass a php variable to javascript

Posted: Sun Nov 02, 2008 6:14 am
by novice4eva
is this what you want??

Code: Select all

echo "<a onClick='changeImage(\"".$filename."\")'> $row2[year]</a>";