views:

62

answers:

4

I have javascript function:

function someAction(thisTd,text){
  alert(text);
  thisTd.innerHTML=text;
  ...
}

And html-file:

<td onclick="someAction(this,<?echo 'Long-long text with <b>html-formatting</b>'?>)"/>

When I use such code function someAction doesn't call (because alert doesn't show) and in the error console in Opera no error is displayed. How to fix this problem?
P.S. I do not use frameworks(JQuery etc.).
UPDATE #1
When I use such code:

<?$encoded=str_replace("\n","",str_replace("\r\n","",$text));echo $encoded?>

It works nice. But I'm not sure, that it work correct in Linux.(I use Windows)

+2  A: 

Make sure that you HTML encode it and put single quotes around the parameter:

<td onclick="someAction(this, '<?echo htmlspecialchars('Long-long text with <b>html-formatting</b>', ENT_QUOTES) ?>')"/>
Darin Dimitrov
A: 

Just put the quotes around the text, you're producing:

Logically, this gives an error.

Use simple quotes or escape double quotes (\")

netadictos
+1  A: 

You should remoce echo tag and the ?

 <div onclick="someAction(this,'Long-long text with <b>html-formatting</b>')">myDiv</div>

and your function is :

function someAction(thisTd,text){
    thisTd.nodeValue=innerHTML
    ...
}
oyo
Text is sample. In fact, there should be variable.
Dublicator
you can do someAction(thisTd,someVariable) and in the javascript call your php script
oyo
+1  A: 

You must wrap the string in single or html encoded double quotes in the first place:

<td onclick="someAction(this, '<?php echo 'yada yada'; ?>');"/>
<!-- OR -->
<td onclick="someAction(this, &quot;<?php echo 'yada yada'; ?>&quot;);"/>

Secondly, the "echo"ed output can contain single or double quotes that can break the javascript string or the html attribute. Assuming that you're using single quotes to wrap the echoed string:

<td onclick="someAction(this, '<?php echo htmlspecialchars( str_replace( "'", "\\'", $that_long_text ) ); ?>');"/>
Salman A
I use such code: <td onclick="someAction(this, "<?echo htmlspecialchars(str_replace( "'", "\\'", $text ), ENT_QUOTES)?/> but it's not work.
Dublicator
I don't see a `?>` in the comment but may be its a typo. But I also do not see the closing `"`. Also, If you're using `"` (correctly encoded as `"`) as the string delimiter then you should replace all `"` with `\"`; not `'` with `\'`.
Salman A
Yes, it's typo. When I use this: onclick="someAction(this, "<?echo htmlspecialchars(str_replace( '"', '\"',$text), ENT_QUOTES);?>")" it's give such code: onclick="someAction(this, " <p>sdf</p> <p><strong>sdfsdf</strong></p> ")"
Dublicator
Assuming that what you pasted was copied from the "view-source" of the generated page, I see that you have double quotes inside the onclick attribute. Encode them or use single quote: `onclick="someAction(this, ' <p>sdf</p> <p><strong>sdfsdf</strong></p> ')"`
Salman A