简体   繁体   中英

Passing PHP variable to JavaScript with special characters

I have a button with an onclick function where i send several php variables to my javascript function. This all works fine except for when i have a ' within the text.

So i would have a button

<button onclick=\"selected_comp('" . preg_replace("/\r|\n/", "", $comp_row['comments']) . "')\"

then i would have a function

function selected_comp(comments){
console.log(comments);
}

I have tried preg_replace and json_encode but both give me errors (json_encode gives me error in general and with preg_replace it works most of the time but whenever this ' character is inside the comments it doesn't work. How can i make sure this gets treated as just plain text whatever character is inside.

error: (index):1 Uncaught SyntaxError: Invalid or unexpected token

If you want your string to be valid javascript string that you can use inside your javascript code (in your example - pass the string to the selected_comp function) you should:

  1. Make sure you don't have line-breaks in your string.
  2. Make sure you don't have quotes inside your string (Note here it depends on the quotes you use in your code - single/double).

So you can:

  1. str_replace(["\\r", "\\n"], ['\\r', '\\n'], $comp_row['comments']);
  2. str_replace("'", "\\\\'", $comp_row['comments']);

And in your code:

<button onclick=\"selected_comp('". 
    str_replace("'", "\\'",
        str_replace(["\r", "\n"], ['\r', '\n'], $comp_row['comments'])
    ) .
"')\"

I used ' because you used it in your original function.

From how your PHP code is written, if the text in $comp_row['comments'] is text then the resulting JS code will be

<button onclick="selected_comp('text')">

(where I added the < and > for clarity).

Now if the text is text with ' embedded it will result in

<button onclick="selected_comp('text with ' embedded')">

Then you clearly see why it fires an error.

There are plenty of different solutions to avoid it, like the one suggested by @Terminus.
But maybe it's not easy to apply without deeply changing your PHP script structure.

So here is a suggestion which may appear a bit weird but keeps using your current code organization:

button onclick=\"selected_comp('" . 
str_replace(["\r", "\n", "'"], ["", "", "\\'"], $comp_row['comments']) . 
"')\"

First you can notice that I changed from preg_replace() to str_replace() (anyway preg_replace() was already overkill).

And the point is that now, not only \\r and \\n are replaced by "nothing" but also ' is escaped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM