Using double quotes in a Javascript alert outputted through PHP code
<? if ($row_count_artifacts['artifact_count'] == '2') { echo "<a href=\"javascript:;\" onClick=\"MM_popupMsg('It appears you still need to add ONE artifact! Click the "Add Artifact" button next to "IV. Artifacts" to enter something you\'d like to share with the GUHSD community.')\"><img src=\"images/alert.gif\" alt=\"Exclamation Point!\" title=\"Incomplete\" align=\"absmiddle\" border=\"0\">"; } ?>
I've always used a backslash (i.e. \) to escape single or double quotes in situations like this, but for some reason my javascript pop-up alert DID NOT work when I escaped the double quotes inside the PHP syntax. The code that didn't worked looked like this:
<? if ($row_count_artifacts['artifact_count'] == '2') { echo "<a href=\"javascript:;\" onClick=\"MM_popupMsg('It appears you still need to add ONE artifact! Click the \"Add Artifact\" button next to \"IV. Artifacts\" to enter something you\'d like to share with the GUHSD community.')\"><img src=\"images/alert.gif\" alt=\"Exclamation Point!\" title=\"Incomplete\" align=\"absmiddle\" border=\"0\">"; } ?>
Escaping with a backslash worked just fine if I used single quotes in the javascript alert text— just not with double quotes. Very strange. By all accounts escaping the double quotes with a backslash should have worked, right? In hindsight, I probably could have made it work had I outputted my HTML in PHP using simple (single) quotes rather than double quotes as this gent recommends, but I didn't feel like it at the time.
So, I ended up getting around this little conundrum by using HTML code for curly or smart quotes (“ for a left curled quote “ and ” for a right curled quote ”) inside the javascript alert like this:
<? if ($row_count_artifacts['artifact_count'] == '2') { echo "<a href=\"javascript:;\" onClick=\"MM_popupMsg('It appears you still need to add ONE artifact! Click the “Add Artifact” button next to “IV. Artifacts” to enter something you\'d like to share with the GUHSD community.')\"><img src=\"images/alert.gif\" alt=\"Exclamation Point!\" title=\"Incomplete\" align=\"absmiddle\" border=\"0\">"; } ?>
2 Comments:
Nice post which Escaping with a backslash worked just fine if I used single quotes in the javascript alert text— just not with double quotes. Very strange. By all accounts escaping the double quotes with a backslash should have worked. Thanks a lot for posting this article.
By Alex, at 6:20 AM
Nice post which Escaping with a backslash worked just fine if I used single quotes in the javascript alert text just not with double quotes. Very strange. By all accounts escaping the double quotes with a backslash should have worked. Thanks a lot for posting this article.
By Lindsey, at 4:30 AM
Post a Comment
<< Home