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.
Related
I'm trying to echo a dynamic a tag which calls a javascript function, but the parameters are not being echoed correctly. They should retain their capitalization and not add spacing. Why is it doing this?
I've tried removing variables and just echoing a straight string with what I want, but it still displays incorrectly.
What I need:
echo '<img src="'.$info[1].'"/>'
Pure String Version:
echo '<img src="/images/calc-eng-desktop.png">'
Outputs:
<a href="/calc" onclick="redirTrackCalcBtn(" test_button_1",="" "="" calc")"="">
<img src="/images/calc-eng-desktop.png">
</a>
Should Output:
<a href="/calc" onclick="redirTrackCalcBtn("Test_Button_1", "/calc")">
<img src="/images/calc-eng-desktop.png">
</a>
I also tried:
echo "<img src=\"".$info[1]."\"/>";
But that still outputs:
<img src="/images/calc.png">
as per Dharman's response I also Tried:
echo '<a href="'.$info[0].'"
onClick=\"redirTrackCalcBtn("'.$bname.'", "'.$info[0].'")\"
><img src="'.$info[1].'"/></a>'
This outputs:
<a href="/calc" onclick="\"redirTrackCalcBtn("Test_Banner_1"," "="" calc")\"="">
<img src="/images/preguntanos-h-es.png">
</a>
Edit for context:
It's for a dynamic banner within the content of a blog powered by WordPress.
You can simplify your expressions using the following technique ...
HTML accepts single quote or double quotes for attributes.
PHP can evaluate variables inside of double quote delimited strings. This can make your expressions much more easier to understand.
So based on this, the answer would be:
<?php
echo "<a href='{$info[0]}' onClick='redirTrackCalcBtn(\"{$bname}\", \"{$info[0]}\")'><img src='{$info[1]}'/></a>";
This will give the following result ...
<a href='/calc' onClick='redirTrackCalcBtn("test_button_1", "/calc")'><img src='/images/calc-eng-desktop.png'/></a>
In your question, you have shown an Pure String Version and what you thought was a normal output. Both of those outputs are wrong. You cannot use something like onclick="redirTrackCalcBtn("Test_Button_1", "/calc")" because the double quote right after the opening parenthesis finishes the onclick attribute which become onclick="redirTrackCalcBtn(". After that, the browser will try its best to find the following attributes and their values. So the spaces that you are seeing are just the natural space between attributes.
In conclusion, there is nothing wrong with echo.
You need to escape one set of the double-quotes, otherwise they are mixed together. Since you went for single-quotes in PHP, you need to use double in HTML/JavaScript and then use single-quotes again, but this time escaped from PHP.
echo '<a href="'.$info[0].'" onClick="redirTrackCalcBtn(\''.$bname.'\', \''.$info[0].'\')" ><img src="'.$info[1].'"/></a>';
The JavaScript variables are enclosed within \'
or
echo '<a href="'.$info[0].'" onClick=\'redirTrackCalcBtn("'.$bname.'", "'.$info[0].'")\' ><img src="'.$info[1].'"/></a>';
The onlick part is now enclosed with escaped quotes, everything else stayed the same.
You have 3 languages mixed together, 3 layers:
PHP will use '
-->HTML will use "
---->JavaScript will use \'
Each one uses double or single quotes and you only have two to choose from. Therefore you need to escape one of them.
A simpler example:
echo '<a onclick="alert(\'hi\')">Hello</a>';
Perhaps a simpler way to overcome quote escaping confusion is to assign the string in a different way. You can remove one layer of quotation by using heredoc notation.
as an aside, your "correct" output is not correct:
onclick="redirTrackCalBtn("Test_Button_1, "/calc")">
<a href="/calc" onclick="redirTrackCalcBtn("Test_Button_1", "/calc")">
<img src="/images/calc-eng-desktop.png">
</a>
Your HTML should look like this:
<a href="/calc" onclick="redirTrackCalcBtn('Test_Button_1', '/calc')">
<img src="/images/calc-eng-desktop.png">
</a>
Using Heredoc notation, you don't have to concatenate and escape, just write it out the way the HTML should be:
$link =<<<LINKINFORMATION
<a href="{$info[0]}" onclick="redirTrackCalcBtn('{$bname}', '{$info[0]}')">
<img src="/images/calc-eng-desktop.png">
</a>
LINKINFORMATION;
echo $link;
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") + "';";
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) );
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));?>" />
?>
<a href="" onClick="return select_item(<embed src=\"player.swf\" allowfullscreen=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" FlashVars=\"id=&flv=1257568908_.flv\" type=\"application/x-shockwave-flash\" width=\"450\" height=\"371\"></embed>')>
The above returns an "unterminated string literal" error.
How to solve this issue. This function is inside smarty template.
Thanks for every answer
I've also run into situations with Smarty where it tries to evaluate Javascript as Smarty template code.
In that case, you need to surround the Javascript with {literal}{/literal} tags.
However, in your case, I think you're missing a single-quote at the beginning of select_item( and a double-quote at the end of the onClick event:
<a href="" onClick="return select_item('<embed src=\"player.swf\" allowfullscreen=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" FlashVars=\"id=&flv=1257568908_.flv\" type=\"application/x-shockwave-flash\" width=\"450\" height=\"371\"></embed>')">
I'm not 100% sure if you really need to backslash-escape the double-quotes that are part of the <embed HTML.
For that amount of markup, I find it easier to read and debug if you don't do it inline as part of the onClick event. I use PrototypeJS so I'd handle it like this
Click Here
//Handle the click event of the above a tag
Event.observe($('doSelectItem'), 'click', function(event) {
var markup = '<embed src=\"player.swf\" allowfullscreen=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" FlashVars=\"id=&flv=1257568908_.flv\" type=\"application/x-shockwave-flash\" width=\"450\" height=\"371\"></embed>';
if( select_item(markup) ) {
//select_item returns true, so let the click event continue
}else {
//select_item returned false so cancel the click event.
Event.stop(event);
}
});
If you get
unterminated string literal
then it basically means that you have started a String, but never ended it. E.g.
var foo = "bar;
Solution is obvious: terminate it:
var foo = "bar";
Another common cause is using the same quotes inside the String as with which the String is wrapped:
var foo = "my mom said "go out!" to me";
You need to escape such quotes then:
var foo = "my mom said \"go out!\" to me";
In your specific case you have " inside the HTML string which is on its turn wrapped inside another "s of the onclick attribute. So:
<a href="" onClick="return select_item('<embed src="player.swf" ...
needs to be replaced by
<a href="" onClick="return select_item('<embed src=\"player.swf\" ...
It looks like ') is missing at the end of your onClick event, hence the JavaScript error. You also need to escape the double quotes. The line should look like:
<a href="" onClick="return select_item('<embed src=\"player.swf\" allowfullscreen=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" FlashVars=\"id=&flv=1257568908_.flv\" type=\"application/x-shockwave-flash\" width=\"450\" height=\"371\">');">
There is so much confusion about escaping quotes in javascript and HTML, especially when they are mixed like this.
Straight off the bat, try to avoid this situation in the first place. HTML is for markup, Javascript is for behaviours. That said...
In Javascript, you escape quotes with a backslash. This is so that when javascript interprets the string it knows where it ends.
var name = 'O\'Reilly';
In HTML, you use ampersands and a character code.
O"Reilly
Just remember that when you are writing code in your HTML, it's not being interpreted by javascript, it's being interpreted by the HTML parser. To a HTML parser, a backslash is just a regular character.
<a onclick="foo("bar");">
Now you see why I'd recommend avoiding the situation in the first place. Here's the alternative:
<a id="myLink">
<script type="text/javascript">
document.getElementById('myLink').onclick = function() {
foo('bar');
};
</script>