Problem passing PHP variable into Javascript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
Jackpotgee
Forum Newbie
Posts: 3
Joined: Thu Apr 26, 2012 12:14 am

Problem passing PHP variable into Javascript

Post 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,
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Problem passing PHP variable into Javascript

Post 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
Jackpotgee
Forum Newbie
Posts: 3
Joined: Thu Apr 26, 2012 12:14 am

Re: Problem passing PHP variable into Javascript

Post by Jackpotgee »

You are a genius, thank you. How to do that has been driving me nuts for ages.
Post Reply