Handling single quote in JavaScript and jQuery - javascript

I am trying to display values in a div of JSP dynamically. The below $('#test${i}${j}') selects a div dynamically as I want, but the HTML part is creating issue for me. ${column} is just a value, for example, accountant, financeMR, etc.:
<c:out value="<script>$('#test${i}${j}').html(${column}); </script>" escapeXml="false" />
In the above I get an error which says "accountant is undefined", etc. The reason being there is no single quote (') wrapping ${column} (in HTML). However, if I try the below, it works in all cases except the cases where the ${column} value contains a single quote. For example, Mng'r:
<c:out value="<script>$('#test${i}${j}').html('${column}'); </script>" escapeXml="false" />
How can I resolve it?

The Apache commons lang library provides escape utilities: http://commons.apache.org/proper/commons-lang/
This should do the trick:
StringEscapeUtils.escapeEcmaScript(inputString);

Related

Nesting quotes in HTML > JavaScript > WebForms or how to call a .NET method in a JavaScript method

Who would think so, but I actually need 3 levels of nested quotes in an ASP.NET WebForms page.
Here's what I have:
<img
src='<% ResolveClientUrl("~/SwissStyleguide/img/swiss.svg"); %>'
onerror="this.onerror=null; this.src='SwissStyleguide/img/swiss.png';"
alt="Confederatio Helvetica"
/>
Now, the first part, assigning a dynamically created URL to the src attribute works fine. The server resolves the given special URL and creates an absolute link for the client to fetch.
But the onerror handler is more tricky: since the src URL to the png image is already in an expression with double quotes, I can not invoke the ASP.NET ResolveClientUrl method, which strictly requires double quotes for the string argument.
I tried to do it like this (does not work!)
<img
src='<% ResolveClientUrl("~/SwissStyleguide/img/swiss.svg"); %>'
onerror="this.onerror=null; this.src='<% ResolveClientUrl("~/SwissStyleguide/img/swiss.png"); %>';"
alt="Confederatio Helvetica"
/>
But without much surprise, Visual Studio complains about this string. The only idea that comes to my mind is to use a string constant to avoid having the innermost quotes, but that seems very ugly.
Is there a way to escape or otherwise specify some or all of the quotes to make that work?
Note: I know about this question: When to use double or single quotes in JavaScript? but changing the quotes does not help in this case.
Well,... this turned out as an instance of the "<%$, <%#, <%=, <%# … what's the deal?" WebForms problem, answered perfectly here: https://stackoverflow.com/a/957321/79485
The solution is to use the equal sign after the percent sign and omit the trailing semicolon. Like this:
onerror="this.onerror=null; this.src='<%= ResolveClientUrl("~/SwissStyleguide/img/swiss.png") %>';"
I'll leave the question and this answer here as a reminder of anyone tripping over this too.
How about placing the attributes from the code-behind instead?
.aspx
<img id="image" runat="server" alt="Confederatio Helvetica" />
.aspx.cs (Page_Load)
image.Attributes.Add("src", Page.ResolveUrl("~/SwissStyleguide/img/swiss.svg"));
image.Attributes.Add("onerror", "this.onerror=null; this.src='" +
Page.ResolveUrl("~/SwissStyleguide/img/swiss.png") + "';";

How do I encode html for Bootstrap popover and tooltip content

This may be a duplicate; it's hard to tell because the key words contain "html" and "content" and even Bing and Google were returning a lot of false positives.
Bootstrap tooltips and popovers support html values for the data-content attribute when data-html=true. However, this isn't valid
<input id="email" class="form-control" type="email"
data-bind="value: Email, valueUpdate: 'afterkeydown'"
data-container="body" data-toggle="popover" data-placement="bottom"
data-title="Email" data-html="true"
data-content="<p>This is <i>your</i> email address.</p>" />
because you can't just put html in the value of an attribute that is itself HTML. It may confuse the parser and is not permitted by the HTML specification.
While it seems to work with Internet Explorer, I really don't feel like testing with fifty different browsers and versions. It certainly does confuse the parser in the Visual Studio 2013 HTML editor. That editor thinks there's no closing quote.
I could dodge this by assigning the attribute from JavaScript in a separate file, but that's clumsy and defeats the separation of concerns.
So, what's the right way to mark this up?
As the accepted answer points out, you can't have a quote " inside a string quoted with ". This problem occurs often. If you want to display text that looks like HTML, then how is the browser supposed to know what it should parse as HTML and what it should simply display.
For example, how do you get a browser to display the text <p></p>
The answer is escaping. Instead of characters like " and <, you use placeholders like " and <
However, the solution of escaping the quotes doesn't work here. Precisely because the browser will not parse it as HTML. If you put escaped quotes in your html, they don't look like quotes to the browser, they look like text.
There is a different solution however: A string that is quoted with " can contain ' without problems. The following is valid:
data-content="<div id='string_in_string' ></div>"
This can be applied to your bootstrap popovers, I've set up a fiddle, it shows how the single quote strings are correctly parsed, while the escaped strings confuse the browser: https://jsfiddle.net/z4t2sud3/3/
This is the code inside the fiddle (the fiddle environment automatically imports bootstrap, jquery, etc)
<mark data-content="
<button class="btnr" type="button">
Doesn't work
</button>
<button class='btn btn-info' type='button'>
Works
</button>
" data-html="true" data-toggle="popover">
Popovered
</mark>
And be sure to activate the popover via Javascript:
$(function () {
$('[data-toggle="popover"]').popover()
})
You can add whatever you want to an HTML attribute as long as it is a valid html attribute value. What is a valid attribute value? What does not contains tags, quotes and so on. So.... and what? The solution is: Scape the string before append it inside the html attribute.
If you are using PHP: http://fi2.php.net/htmlspecialchars
Or Twig: http://twig.sensiolabs.org/doc/filters/escape.html
If you are using jquery, when you do $el.data('my_scaped_json) will be converted to whatever it was originally, such a json object or html-string: $( $el.data('my_scaped_html) );

impossible to escape single quotes in XML

please help me with this issue. I have a php file which generates XML. I have the following code that I can not escape a JS script within XML as follows:
$xml_after='<html>'.htmlspecialchars('
<div class="options" id="options_'.$tables_row['id'].'">
<a class="insidetable" href="" title="'.$lang['delete'].'"
onClick="show_confirmation(\''.$messages['delete_table'].'\',\''.$lang['close'].'\',hide_element(\'confirmation\');\''.$lang['delete'].'\',remove_table(\''.$tables_row['id'].'\');hide_element(\'confirmation\');\');return false;\" ><img src="../images/interface/icons/delete.png" />
</a></div>').'</html>';
The problem is in onclick functions..
Please help, full day losted already , thank you
Be aware that htmlspecialchars() escapes < and >, too. You have to use it on each value separately, not on the complete html fragment.
htmlspecialchars() has an option that escapes all quotes.
var_dump(htmlspecialchars("Escaping: <>&'\"", ENT_QUOTES));
Ouptut:
string(35) "Escaping: <>&'""
But it would be better to use DOM and let it take care of the escaping.
Additionally, I suggest using data-* attributes in HTML. The Javascript can read the attributes and bind the logic to the elements. This separates the actual JS logic from the HTML.
I think your code is incorrectly formatted
$xml_after='<html>'.htmlspecialchars('<div class="options"
id="options_'.$tables_row['id'].'">
<a class="insidetable" href="" title="'.$lang['delete'].'"
onClick="
show_confirmation(\''.$messages['delete_table'].'\',\''.$lang['close'].'
\', hide_element(\'confirmation\');\''.$lang['delete'].'
\', remove_table(\''.$tables_row['id'].'\');
hide_element(\'confirmation
\');
\');return false;\" >
<img src="../images/interface/icons/delete.png" />
</a></div>').'</html>';
after each of the functions inside the show_confirmation functions you have a ; which isn't valid in a function calls parameter list
On the last line of the onClick function:
\');\');return false;\" >
The second \' is unmatched and the double quote \" shouldn't be escaped as far as I can see change that and maybe it will work for you.

Put JSON data into html form input hidden?

I'm building a rich web application that uses a lot of data. When I'm building it I found that I was repeating myself over and over.
This is the problem. I need to put hidden application logic into HTML elements to represent the data being viewed by the client.
This is a solution I found some time ago:
<a href="bla" data-itemId="1" .... more data.
There are two problems with this method.
I can't represent arrays.
It's just ugly.
I searched for a solution but did not find anything. I also went to facebook, opened firebug,
and found this:
{"actor":"19034719952","target_fbid":"454811929952","target_profile_id":"19034719952","type_id":"7","source":"1","assoc_obj_id":"","source_app_id":"","extra_story_params":[],"content_timestamp":"1324385453","check_hash":"9eabc3553e8a2fb6"}
This json was inside an input[type=hidden] element.
I tried to do the same thing with json_encode();
<input type="hidden" name="track" value="{"_id":{"$id":"4eee908f615c2102e9010000"},"link":"george-wassouf-flag-of-my-heart-longing","file":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","lyrics":null,"freezed":false,"hits":0,"images":{"large":"\/assets\/static\/default.track.large.jpg","thumb":"\/assets\/static\/default.track.thumb.jpg","icon":"\/assets\/static\/default.track.icon.jpg"},"duration":"300","created":{"sec":1324257423,"usec":78000},"albums":[{"_id":{"$id":"4eee8d63615c21f6e7000000"},"names":{"ar":"\u0643\u0644\u0627\u0645\u0643 \u064a\u0627 \u062d\u0628\u064a\u0628\u064a","en":"Kalamak ya Habibi"},"link":"george-wassouf-kalamak-ya-habibi","images":{"original":"\/m\/pics\/albums\/o.4eee8d612c3183.11879972.jpg","poster":"\/m\/pics\/albums\/p.4eee8d63967072.02645896.jpg","large":"\/m\/pics\/albums\/l.4eee8d63a89111.20372767.jpg","small":"\/m\/pics\/albums\/s.4eee8d63b18927.47242533.jpg","thumb":"\/m\/pics\/albums\/t.4eee8d63b7f1f4.11879932.jpg","icon":"\/m\/pics\/albums\/i.4eee8d63bf1304.59902753.jpg"}},{"_id":{"$id":"4eee8d63615c21f6e7000000"},"name":"Kalamak ya Habibi","link":"george-wassouf-kalamak-ya-habibi"}],"name":"Flag of my heart longing","title":"Flag of my heart longing","mp3":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","poster":"\/m\/pics\/artists\/p.4eee85cd7ed579.65275366.jpg","artists":[{"_id":{"$id":"4eee85cd615c21ece6000000"},"name":"George Wassouf","link":"george-wassouf"}]}" />
But when I try getting the value I get this {.
I have tried all constants like JSON_HEX_TAG and did not find any questions of this type.
How can I put JSON into HTML correctly and then get it with jquery/javascript?
Your string is correct, but it cannot be defined in HTML because it contains double quotes.
HTML requires you to escape double quotes when you are defining a String that is itself enclosed within double quotes. The appropriate way of doing this is using the HTML entity:
value="""
From PHP:
Use htmlspecialchars or htmlentities (http://www.php.net/manual/en/function.htmlspecialchars.php). In any case, you normally should be using this over EVERY value you write to the client browser (not doing so may result in security risks).
From Javascript:
If you need to do this from Javascript, you can programatically set the value of the hidden element (provided your JSON string is already contained in a Javascript variable). This way you don't have to worry about encoding the string literal:
hiddenElement.value = yourString;
In order to get an escape function you can use, maybe check this thread: Escaping HTML strings with jQuery .
Best way for me was to use html & quot;
for example i do this:
<input type="hidden" id="v" value="[{"id":"1"}]" >
instead of
<input type="hidden" id="v" value="[{"id":"1"}]" >
in your input tag, the value attribute in which you are trying to put json array. Look at it. you are putting ". Second " is ending the attribute value. thus it is being interpreted as value = "{". you need to escape those ". Use single quotes ' instead. And check then
It seems my answer is late, but I want to contribute to those who come later.
Before coming here you have the concept of HTML.Use single quotes ' , Should not do that, although it still works, it is against the HTML principle .
The best way is: Use htmlspecialchars or htmlentities. #jjmont said above.
I have a small example:
<input id="jsondata" value="<?php echo htmlspecialchars( json_encode($data), ENT_COMPAT ); ?>" >
||
<input id="jsondata" value="<?php echo htmlspecialchars( json_encode($data), ENT_NOQUOTES ); ?>" >
php
set array in
<input type="checkbox" name="deviceInfo" value="<?php print_r(json_encode(array_filter($array_data), JSON_FORCE_OBJECT));?>" />
?>

Passing rendered html to a javascript function

I have some html code rendered on the server side. This is passed to a jsp which renders a javascript-call with this html:
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", "${content}");
</script>
content is like
"
This is a <p class="xyz">test</p>
"
My problem is that - according to the quotes in 'content' - the javascript-call is wrong as it is rendered to
<script type="text/javascript">
window.parent.${param.popup_return}("ybc", "This is a <p class="xyz">test</p>");
</script>
Does anyone know how I can solve this (besides manually replacing all quotes)?
Use a JSON encoder to create the encoded strings.
But you'll also have to ensure that the output doesn't contain the sequence </ in string literals, which is invalid in a <script> block (</script is the version that will also break browsers).
Many JSON encoders either by default or optionally will encode to <\/ or \u003C/ to avoid this problem.
I use this:
<div id="result" style="display:none">
${content}
</div>
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", dojo.byId("result").innerHTML);
</script>
This seems to work perfectly
You aren't using JSTL here (you originally tagged the question with only JSTL). You are using EL in template text. It get printed plain as-is. You'd like to use JSTL core <c:out> to escape predefined XML entities (which also works for HTML in this particular case, quotes is among the escaped XML entities).
window.parent.${param.popup_return}("<c:out value="${helpId}" />", "<c:out value="${content}" />");
An alternative (if you hate that the JSP syntax highlighter or validator bugs/jerks about nested tags/quotes) is the JSTL function fn:escapeXml():
window.parent.${param.popup_return}("${fn:escapeXml(helpId)}", "${fn:escapeXml(content)}");
Have you tried using single quotes instead of double quotes? i.e. changing "${content}" to '${content}'

Categories