how do I pass a php variable to javascript
Posted: Fri Oct 31, 2008 10:04 am
I have a page that has this Javascript at the top.
And down in the page is PHP that produces this code:
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.
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.
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>
Code: Select all
echo "<a onClick='changeImage()'> $row2[year]</a>";Here is the code for the image that will be changed.
Code: Select all
<img src="images/blank_graph.png" name="graph">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.