yehster wrote on Friday, November 30, 2012:
Ok… It makes sense that both addslashes and attr are needed for this to work. Addslashes is escaping for javascript, while attr is escaping html.
With just addslashes, the html generated is as follows:
<a href='' onclick='return selcode("ICD9", "351.0", "", "Bell\'s palsy")'>Bell's palsy</a>
The single quote in Bell’s closes the onclick attribute string prematurely and you have invalid html.
The slash doesn’t fix it because the issue is with the HTML, and backslash does not do anything in html. The backslash does escape the single quote for javascript, which is unneeded since the javascript literal uses double quotes, but it doesn’t hurt anything.
For double quotes. With just attr, the browser parses the HTML like this:
<a onclick="return selcode("ICD9", "495.7", "", ""ventilation" pneumonitis")" href="">
The javascript function call to selcode is invalid because of the double quotes make the 4th parameter incorrectly formed. The slashes are needed to escape double quote within the string for javascript.
Interestingly, doing the escape sequence in the other order
addslashes(attr($itertext))
doesn’t work because if the quotes get escaped for html first, the slashes don’t get added for the javascript.
Anyway. Javascript string literals do need to be escaped with addslashes. HTML attributes need to be escaped with attr. Since in this case onclick is an HTML attribute which contains javascript literals it does need both.