Jump to content

[SOLVED] how do I pass a php variable to javascript


Darkmatter5

Recommended Posts

I have a page that has this Javascript at the top.

 

<script type="text/javascript">
<!--
var imageURL="<?php echo $filename; ?>";

if(document.images) {
    var graph=new Image();
    graph.src=filename;
    
    var blank=new Image();
    blank.src="images/blank_graph.png";
}
function changeImage(filename) {
    if(document.images) {
        if(imageURL=="images/blank_graph.png") imageURL=filename;
        else imageURL="images/blank_graph.png";
        
        document.myImage.src=imagesURL;
    }
}
//-->
</script>

 

And down in the page is PHP that produces this code:

 

echo "<a onClick='changeImage('$filename');'>$values[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.

<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

I had tried to pass php in javascript. Javascript is client-side and PHP is server-side so it won't work, at least it never did for me. Try setting that variable in javascript also I guess. You would have to set the extra variable in each document but that won't take long. I'm sure other people here have better suggestions then that though

I finally got it completely working, with PHP variables passed to Javascript.

 

Here's the code that works.

 

<script type="text/javascript">
<!--
var imageURL="images/blank_graph.png";

if(document.images) {
    var graph=new Image();
    graph.src="images/graphs/" + filename + ".png";
    
    var blank=new Image();
    blank.src="images/blank_graph.png";
}
function changeImage(filename) {
    if(document.images) {
        imageURL="images/graphs/" + filename + ".png";
        
        document.graph.src=imageURL;
    }
}
//-->
</script>

 

Here's the onClick event:

echo "<a onClick='changeImage($row1[folder_id]$minyear)'> $minyear</a>";

 

Enjoy!

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.