tags:

views:

39

answers:

3

I have the following php code

$bigImageSrc = 'images/'.$prodXML->bottles->bottle[$i]->bigImage;
$text = $prodXML->bottles->bottle[$i]->title;
$title = $prodXML->bottles->bottle[$i]->text;    
echo "<a href=javascript:void(0); onClick=showProduct('$bigImageSrc', '$text', '$title');>

but I'm getting this error:

syntax error
showProduct('images/image1.jpg',

It works for just one var in the showProduct function.

Any ideas where I'm going wrong?

+1  A: 

Your html link is printed out without quotes in it. While I have no idea if this will work in all browsers, it may be a good idea to use them anyway.

Kurt Du Bois
+6  A: 
<a href=javascript:void(0); onClick=showProduct('$bigImageSrc', '$text', '$title');>

You have no quotes around your onClick attribute, which means that the space after '$bigImageSrc', is interpreted as the end of that attribute value.

You should enclose every attribute in HTML within quotes, to prevent a lot of problems.

Eg.

echo "<a href=\"javascript:void(0);\" onClick=\"showProduct('$bigImageSrc', '$text', '$title');\">";

You should also not be using javascript:void(0); as an href attribute, as it breaks when Javascript is disabled or someone tries to "open in new window", "bookmark", "open in new tab" etc on that link. But that's a separate issue.

thomasrutter
thanks thomas - what's the better than using javascript:void(0); ?
daidai
It's better to actually link to something that would work, if possible. Note that the existence of the onclick handler means that if Javascript is enabled, this will be irrelevant, but it's a good idea to have a link there that would work anyway were it not for Javascript, or in case someone tries to open the link in a new tab, copy/bookmark the link, etc. I understand that it is more work to do this. Another issue is one of accessibility; an onclick handler will only activate if someone uses the mouse, but what if they select it via a keyboard or other device?
thomasrutter
A: 

It's a lot easier to work with lines like that if instead of echoing, you just go out of PHP mode. Then you don't have to worry about the different kinds of quotes.

$bigImageSrc = 'images/'.$prodXML->bottles->bottle[$i]->bigImage;
$text = $prodXML->bottles->bottle[$i]->title;
$title = $prodXML->bottles->bottle[$i]->text;    
?>
<a href="javascript:void(0);" onClick="showProduct('$bigImageSrc', '$text', '$title')"

Even better, don't use onclick. Assign the event handler with attachEvent/addEventHandler ( http://www.quirksmode.org/js/events_advanced.html ) or something like jQuery bind/.click. So much easier.

Mark Snidovich