Displaying Quotes In Alerts Using JavaScript And PHP

October 22nd, 2009  | Categories: JavaScript, PHP

ISSUE
I’ve been struggling with this problem off and on now for the past like six months. The issue is properly displaying single and double quotes in JavaScript on a onclick action. PHP is being used to get the data for the string.

The data without single or double quotes displayed fine in the alert box, but the other data didn’t.

In a nut shell, I needed:

<a onclick="javascript: alert('$data');">?</a>

The trick was escaping $data to display the proper PHP first, then JavaScript.

The $data string I kept testing was:

Has the ability to quote the Godfather series on command. Must be able to complete a quote or a scene by the slightest dialogue.

“Go to the mattresses!”

FIX
As I said, I tried just about everything trying to get $data to display single and double quotes in the alert box. I started simple by replacing the with /’ and with /”, to no avail. I also tried using the htmlspecialchars function, but that didn’t work either.

Furthermore, I tried to replace the double quotes with single quotes and escape the string. It still didn’t work.

When I finally got close to solving the problem, I realized it wasn’t necessarily escaping the quotes, it was also escaping the line breaks. Since PHP and JavaScript have the same line break escape (\n), it was a little tricky.

I finally got a script off the internet to escape the string and put the special characters into their HTML entities. It didn’t work, but I built on that same idea.

My script is now:

$data = preg_replace("/\r?\n/", "\\n", htmlspecialchars(str_replace("'", "\'", $data)));

echo "<a onclick=\"javascript:alert('$data');\">?</a>\n";

Works like a charm.

  1. October 22nd, 2009 at 23:14
    Reply | Quote | #1

    Hello from Russia!
    Can I quote a post in your blog with the link to you?

  2. October 23rd, 2009 at 14:43
    Reply | Quote | #2

    @Polprav
    Sure, anyone can.

TOP