how do I pass a php variable to javascript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
Darkmatter5
Forum Newbie
Posts: 2
Joined: Fri Oct 31, 2008 8:36 am

how do I pass a php variable to javascript

Post 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.
User avatar
novice4eva
Forum Contributor
Posts: 327
Joined: Thu Mar 29, 2007 3:48 am
Location: Nepal

Re: how do I pass a php variable to javascript

Post by novice4eva »

is this what you want??

Code: Select all

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