ian
ian

Reputation: 12335

How can I properly escape JavaScript in JavaScript?

This might be something I can't do but...

parent.document.getElementById('<?php echo $_GET['song']; ?>')
  .innerHTML = '<img src="heart.png" onmouseover="heartOver('');" >';

The onmouseover="heartOver(''); portion breaks my JavaScript. Is there a way to escape the quotes so I can do this?

Upvotes: 2

Views: 1146

Answers (3)

eyelidlessness
eyelidlessness

Reputation: 63519

Escape nested quotes with a backslash: \'

Also, never echo user data without validating or sanitizing it:

$song = $_GET['song'];

// Validate HTML id (http://www.w3.org/TR/REC-html40/types.html#type-name)
if(!preg_match('/^[a-z][-a-z0-9_:\.]*$/', $song) {
    // Display error because $song is invalid
}

OR

// Sanitize
$song = preg_replace('/(^[^a-z]*|[^-a-z0-9_:\.])/', '', $song);

Upvotes: 3

Ryan Brunner
Ryan Brunner

Reputation: 14851

Your issue is with escaping quotes. You can escape either a single or double quote by replacing ' or " with \' or '".

So your code would be:

parent.document.getElementById('<?php echo $_GET['song']; ?>').innerHTML = '<a href="heart.php?action=unlove&song=<?php echo $song; ?>" target="hiddenframe"><img src="images/heart.png" alt="Love! onmouseover="heartOver(\'\');" width="16" height="16" border="0"></a>';

Upvotes: 1

Greg
Greg

Reputation: 321578

It's all just a matter of escaping the quotes properly.

parent.document.getElementById('<?php echo $_GET['song']; ?>').innerHTML =
    '<a href="heart.php?action=unlove&song=<?php echo $song; ?>" target="hiddenframe">'
    + '<img src="images/heart.png" alt="Love!" onmouseover="heartOver(\'\');" width="16" height="16" border="0"></a>';

Also you're missing and end quote for the alt attribute.

Upvotes: 5

Related Questions