views:

23

answers:

2

Hey Guys,

I'm trying to concatenate PHP variables into an "onclick" function.

Here is the line I'm having trouble with (look for the "onclick" part):

$imagecontent = '<div class="imagensfw" id="image'.$id.'" style="width:'.round($wd).'px;height:'.round($ht).'px;" onclick="viewimage(image'.$id.','.round($wd).','.$url.');"><p>Image</div>';

I'm particularly having trouble with concatenating the $url variable. I'd want to put it between quotes, but if I do so, the "onclick" function becomes all messed up (when the code is displayed in the browser).

I think that putting the URL address ($url variable as a parameter in the onclick) between quotes will fix the error its shooting:

Error : missing ) after argument list

Here's my short Javascript function if you're interested:

function viewimage(id,width,url){
    var image = document.getElementById(id);
    image.innerHTML = '<img src="'+url+'" width="'+width+'" alt="Image" />';
}

Here's what I tried but didn't work (i.e. messed up the code):

onclick="viewimage(image'.$id.','.round($wd).', " '.$url.' " );"

(Noticed the double quotes added between the $url variable).

Thank you for your time.

A: 

Have you tried using variable parsing? From the link's example:

$beer = 'Heineken';
echo "He drank some ${beer}s";

This should simplify the construction of your string.

Kaleb Brasee
No, sadly, it doesn't seem to work.
A: 

Silly me, I just noticed an error on my part. I thought we could use double quotes in an "onclick" function. Turns out not, we have to use single quotes ( ' ). It fixed my problem. Thanks!