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.
Related
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.
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);
Following my code:
<div onclick="this.innerHTML='<div onclick=\"<img src=/*how to do here?*//>\">abc</div>'">a</div>
I would like to do everything on one line, can I specify the address of the image with the current example code or not?
Use " to represent a " character in an HTML attribute value delimited with " characters.
(Use & to represent a & character in an HTML attribute value, so if you want to nest insanely then: ")
But don't do this.
Writing everything on a single line in not a virtue.
Writing JS in an onclick attribute instead of a .js file is not a good thing.
Use addEventListener and friends.
Can anyone help me to convert this to proper JavaScript?
<script>var datePostForAll = '<div class='date-header'><data:post.dateHeader/></div>';</script>
Thank you!
:*
It is proper JavaScript. It's the same as writing:
<script>
var datePostForAll = "<div class='date-header'><data:post.dateHeader/></div>";
</script>
They're used ' instead of an apostrophe so they don't have to escape ' and " marks inside the string. The <data:post.dateHeader/> is custom Blogger markup and will be evaluated when it is run. Because the contents of <data:post.dateHeader/> may include quote marks, they chose to wrap the string in ' to prevent accidentally introducing unescaped elements into the string. Regardless, as this will be outputting a date, wrapping it in quotes should be fine.
I have a form where users can enter any HTML.
var title = "Cool Check This"
As you can see, the variable is having " but it can be also '. It causes an error if there is ". What is better way to fix this? Storing escaped string in database like below?
$title = str_replace('"', "'", $_REQUEST['title']); // Replace double quote with single quote as js variable above is wrapped with double quotes.
Or escape it before showing on page? Anything in jQuery like escape that can help here?
var title="Cool Check This"
Well, you cannot escape it using JavaScript because JavaScript needs to see what you want to escape and you want to escape that. If you use PHP, you can use addslashes() prior to inserting into JavaScript.
Anyways, you should be careful of allowing to insert any HTML. Wrongly escaped HTML (like allowing to insert <script>) can allow to do various dangerous stuff, like stealing all cookies.