Passing PHP variable to JavaScript with special characters - javascript

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

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.

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:
Make sure you don't have line-breaks in your string.
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:
str_replace(["\r", "\n"], ['\r', '\n'], $comp_row['comments']);
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.

Related

Using user input inside JavaScript breaks code

I am using user input inside JavaScript. And of course to be safe my framework is changing some symbols to HTML codes. But for some reason that breaks my JavaScript. So for example this works:
<a onclick="alert('hello')">Hello</a>
But this doesn't:
<a onclick="alert('hel l' lo')">Hello</a>
Why doesn't the below work and how can I make it work?
' is HTML for '. The HTML is parsed and the result passed to the JavaScript compiler so your JavaScript is alert('hel ' lo') and you can't have an unescaped ' in a string literal delimited with ' characters.
Escaping data to make it safe to insert into HTML is not enough to make it safe to insert into JavaScript which is then inserted into HTML in turn.
Store the user input in a data-* attribute (which is plain HTML so you can use ' safely) and then read the attribute from your JavaScript.
You're inserting a character reference for a single quote '.
Even though you're using ', when it hits JavaScript, it's a quote mark. Therefore, you're ending the string literal and causing a syntax error.

Using $1 as a variable in javascript

I'm trying to parse a customisable block of text, which I load from a file. Simplifying it a bit, let's say, I'm trying to convert every block of text which appears inside curly brackets into a thing you can click to be javascript-alerted with the aforementioned text.
Problem is, passing $1 into the alert. $1 doesn't play like a variable. anyway, it started OK:
var text='Information here: {Thanks for clicking the info link}';
text=text.replace(/{(.+)}/g,'[<span onclick=\"alert(\\'\$1\\')\">click me</span>]');
document.write(text);
So far, so good. I click where it says "[click me]" and the message "Thanks for clicking the info link" comes up as a javascript alert.
But sometimes I want to put a message with a " or a ' into the curly brackets.
var text='Information here: {Thanks for clicking the "info" link}';
text=text.replace(/{(.+)}/g,'[<span onclick=\"alert(\\'\$1\\')\">click me</span>]');
document.write(text);
simply fails to alert. If I 'view selection source', it gives:
Information here: [<span onclick="alert('Thanks for clicking the " info"="" link')"="">click me</span>]
I've tried every combination of escaping the " marks, but no joy.
I thought of replacing " with ", but $1 isn't a variable!
Any ideas? And yes, I do want to do this! :-)
Thanks!
Use single \ for escaping ' and although there is no need to escape " within single quoted string.
var text='Information here: {Thanks for clicking the info link}';
text=text.replace(/{(.+)}/g,'[<span onclick="alert(\'$1\')">click me</span>]');
document.write(text);
I have no idea whether my idea holds any grounds at all here as the idea popped into my head - but what if you were to use (ignoring quotes, ironically) '"' rather than attempting to escape the quotes themselves?
Edit: I'm an idiot, use (without spaces) '& quot ;'

php echo outputting html as text

I am trying to use php to construct html code containing onclick="Javascript" within
i keep getting an error saying that i am missing a } within the console, however this is not the case.
despite the error the site displays perfectly
I then followed this post
How should I echo a PHP string variable that contains special characters?
and used the method htmlentities
at first it appeared to work correctly however i must have changed something because now it outputs the html string as text and not displaying the element
this issue is present across different platforms/browsers, so i dont believe that it is cache related problem.
there are other elements within the php script that output the html correctly, it just appears that its this line.
Thanks in advance
echo htmlentities('<h2 class="page_title">' . $db_field['Title'] . '</h2><a onClick="showAndroidToast(' . $_SESSION['user_id'] . ',' . $db_field['ID'] . ')"><img src="/mobile/images/plus.png" style="width:25px;height:25px;float:right;margin-top:15px"></a>');
You should not use htmlentities() on strings that you actually want to be interpreted as HTML, since it will convert the < and > into entities so they display literally. Just call it on the variables that you don't want interpreted:
echo '<h2 class="page_title">' . htmlentities($db_field['Title']) . '</h2><a onClick="showAndroidToast(' . $_SESSION['user_id'] . ',' . $db_field['ID'] . ')"><img src="/mobile/images/plus.png" style="width:25px;height:25px;float:right;margin-top:15px"></a>');
Why such violence?
here is how to output templates using PHP :
<?php
//blablabla my php stuff here...
?>
<h2 class="page_title">
<?=htmlentities($db_field['Title'])?>
</h2>
<a onclick="showAndroidToast('<?=$_SESSION[\'user_id\']?>','<?=$db_field[\'ID\']?>');
<img src="/mobile/images/plus.png" style="width:25px;height:25px;float:right;margin-top:15px">
</a>
Whenever you call htmlentities(), whatever in it will be translated into characters that the browser interprets as literal symbols to show. This is how we can tell browsers to display HTML and code without actually interpreting it. It also allows us to show symbols we don't want the browser to accidentally parse. If you have a string containing HTML that you want to be interpreted by the browser, DO NOT use htmlentities().
You don't want:
print htmlentities("<h1>I have a < and > sign I don't want interpreted</h1>");
You actually do want:
print '<h1>' . htmlentities("I have a < and > sign I don't want interpreted") . '</h1>';
Read the docs: http://php.net/manual/en/function.htmlentities.php

Cross-language string escaping

I have a string in C# that contains an error message. This message could contain single quotes or double quotes or both, but I am free to manipulate the string however I need (as well as the HTML/Javascript).
For example, the following messages could be displayed (content isn't important, just the fact they could contain single or double quotes):
The following error has occurred: "You dun goofed."
The specified path isn't valid.
The following error has occurred: "I'm a goof"
This string is inserted into HTML as an alert inside of an onClick handler. That sounds complicated so let me show what I mean:
<a onClick="alert('myContentGoesHere')">View Error</a>
I'm able to get the single quotes to display by replacing ' with \' in C#. However, my attempts to similarly escape " has resulted in an odd number of backslashes which terminates the onClick attribute and causes invalid HTML.
So far I have tried to replace " with:
\"
\\"
"
\"
No dice. I feel like I might be approaching this from the wrong angle so if you have a solution which goes beyond a string replace, I'm all ears. Thanks for any help you can offer.
To make the value work as a string literal in JavaScript you need to escape the string delimiter and backslashes. Then you need to HTML encode the JavaScript so that it works as a value in the HTML attribute.
Example:
string code =
"<a onClick=\"" +
HttpUtility.HtmlEncode(
"alert('" +
myContentGoesHere.Replace("'", "\\'").Replace("\\", "\\\\") +
"');"
) +
"\">View Error</a>";
If the string can contain control characters, you would need to replace them too. Add the ones that you need from:
.Replace("\r", "\\r")
.Replace("\n", "\\n")
.Replace("\b", "\\b")
.Replace("\t", "\\t")
.Replace("\v", "\\v")
.Replace("\f", "\\f")

ENT_QUOTES in a JS string

I have this function :
function change_this(my_str)
{
$('#myDiv').html('<input value=\''+my_str+'\'>');
}
When I call this function with this :
onclick=change_this('Test '');
I see in the debugger that ' has been turned to a quote, and therefore the script does not work.
So my question is: how can I send a quote inside a string to a JS function?
I'm sure I'm not the first person to face this issue, I googled but did not find any simple explanations / answers.
You have two problems. This is because you have HTML embedded in JavaScript embedded in HTML which you are then generating HTML from by mashing together strings of JavaScript. You switch languages so many often it makes my head spin.
Problem 1: Getting the right string into the function
To include a single quote inside a string delimited by single quotes in JavaScript, you must escape them with a \.
onclick="change_this('Test \'');"
There is no need to use character references here. There are no ' with special meaning in the HTML. You would need to use ' three times if you had used ' instead of " to delimit the attribute value.
I'd avoid onclick entirely and favour data- attributes and JS event binding.
<input type="button" data-foo="Test '">
$("[type=button]").on('click', function (event) {
change_this( $(this).data('foo') );
});
Problem 2: Getting the right string into the HTML attribute value.
With the approach you are taking, you would need to convert the ' to '. Note that you would have to do it programatically because if you had it in the onclick attribute then it would be converted to ' by the HTML parser before the JavaScript engine even saw it.
Don't use your current approach though. Mashing strings together to make HTML is a nightmare.
Use DOM or something jQuery that vaguely resembles DOM.
var input = $("<input />").val(my_str);
$('#myDiv').empty().append(input);

Categories