Page 1 of 1

Problem passing PHP variable into Javascript

Posted: Tue May 01, 2012 1:58 am
by Jackpotgee
Hi all,

I have the following php script

Code: Select all

	
$img2 = $img2_id.$img2_name;
$img2_thumb = "thumb_".$img2_id.$img2_name;
echo "<div id='viewadd_image2' class='smallimage'><img src='uploads/".$img2_thumb."' onclick = 'display_img($img2)'/></div>";
the output of $img2 will be a number followed by a name of an image.
eg. 102rubberduck.jpg

I then want to pass this variable into a javascript function which allows me to display the image inside a selected DIV

Javascript:
<script type="text/javascript">

function display_img(img)
{
document.getElementById("viewadd_mainimage").innerHTML = "<img class ='image' src='UPLOADS/" + img + "'/>";
}

</script>

The problem i am having is that the variable starts with a number and is therefore creating an error in Javascript.
From mozilla i'm getting the following message:

Timestamp: 1/5/2012 14:57:05
Error: identifier starts immediately after numeric literal
Source File: http://localhost/DuckLa/viewadd.php?id=125
Line: 1, Column: 12
Source Code:
display_img(102Rubber duck.jpg)

Any help would be grand. Thanks in advance,

Re: Problem passing PHP variable into Javascript

Posted: Tue May 01, 2012 10:23 am
by twinedev
You just need to wrap it with quotes, think of $img2 as a string you would use (cause it is holding a string) so you would need quotes around it.:

Something along the lines of:

Code: Select all

onclick = 'display_img(\"$img2\")'
Note the escaping of the double quotes is needed so echo actually outputs them instead of considers them closing then opening quotes for the string you are echoing.

-Greg

Re: Problem passing PHP variable into Javascript

Posted: Tue May 01, 2012 11:38 pm
by Jackpotgee
You are a genius, thank you. How to do that has been driving me nuts for ages.