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));?>" />
?>
Related
I want to know if javascript methods auto-escape quotes, because this code work:
Example #1
<?php $foo ="hey a quote ' "; ?>
<input type="text" value="<?php echo $foo; ?>" id="foo" />
<script>
bar = document.getElementById('foo').value;
alert(bar+'there is a quote, will it work? ,');
</script>
It displays the alert fine, but this one:
Example #2
<?php $foo ="hey a quote ' "; ?>
<button onclick="alert('<?php echo $foo; ?>');">test</button>
...doesn't.
Obviously, it's because the quote isn't escaped with a \.
But then again, neither is it in the first example, so why is that so ?
Does javascript's method auto-escape quote when it picked stuff from DOM ?
Or is it just the value() method maybe ?
I've found nothing, so if you have even the beginning of an answer, I''ll be glad.
PHP is processed on the server, producing HTML (including embedded javascript in this case). This happens before the HTML is sent to the browser to interpret, including any JS.
You will see if you inspect the generated HTML source, that your second example becomes:
<button onclick="alert('hey a quote ' ');">test</button>
which isn't valid JS syntax.
Your first version works basically because you do not have an extraneous single quote in the code your PHP string is inserted into. The insertion instead produces:
<input type="text" value="hey a quote ' " id="foo" />
which is perfectly fine. And that value is then passed on to the alert call in the JS.
The difference is really that in the first code example, the quote appears in a context where there are no wrapping single quotes, so there is no ambiguity. If you would have wrapped the HTML attribute values with single quotes (which is valid HTML also), you'd have a problem:
<?php $foo ="hey a quote ' "; ?>
<input type='text' value='<?php echo $foo; ?>' id='foo' />
In that case the single quote should have been escaped as an HTML entity: ':
<?php $foo ="hey a quote ' "; ?>
<input type='text' value='<?php echo $foo; ?>' id='foo' />
Now in the second code example you provided, the single quote will appear in wrapped single quotes (for the string literal passed to alert). This is an issue, because the single quote will now end the string literal, and the characters following it will lead to a syntax error.
Here the quote appears in a JavaScript string literal (the alert code), not as in the HTML context of the first example. In JavaScript string literals, single quotes can be escaped with the backslash.
So in both cases (HTML or JavaScript) you could need a form of escaping. They are different.
Note that none of this is related to PHP.
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 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);
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.
I know I can use \', but that's not the point here. Let's say I have the word "can't". It has "'" in it now. This goes in to a var in a function like so:
function active(id,clas,match,hometeam,awayteam){
So let’s say hometeam has the value of "can't". When I try to use this code:
$('#test').html(hometeam + " VS " + awayteam);
It's not working, because essentially it has:
$('#test').html(can't + " VS " + awayteam);
How do I solve this?
EDIT:
I think the problem is not in the jQuery. The line that calls this function is this line:
<input type="button" id="btn" value="1.4" class="butta" onmousedown="active('btn','buttdowna','match1','hometeam','awayteam')" />
So how do I escape this?
EDIT: I haven't found the perfect solution, so I just changed the word in my database and added the "\" for now...
This should work. If the contents have double quotes then wrap the string in single quotes and escape single quotes inside.
var hometeam = '"can\'t"';
$('#test').html(hometeam + 'VS' + awayteam)
The values returned by variables do not need to be escaped in javascript. If you are having a problem there is some other underlying issue.
EDIT: Per your question edit you will need to escape the value in the function call, if you were to use can't as one of your parameters you would need
<input type="button" id="btn" value="1.4" class="butta" onmousedown="active('btn','buttdowna','can\'t','hometeam','awayteam')" />
The problem is that you are using string operations to build HTML. Use jQuery/DOM methods instead and you won't have issues with this.
Another way would be escaping the quotes but compared to the previous suggestion that's just really ugly.
Since you are creating the HTML in PHP, do something like this:
echo '<input type="button" id="btn" value="1.4" class="butta" onmousedown=\'active("btn","buttdowna","match1",'.htmlspecialchars(json_encode($foo)).', '.htmlspecialchars(json_encode($bar)).');\' />';
You can change the HTML Part like this it will work,
<input type="button" id="btn" value="1.4" class="butta" onmousedown=active("btn","buttdowna","match1","can't","awayteam") />
In an HTML attribute without Quotation also work. Quotation is used to group. Example) title="Click Event" will work and title=Click Event will take the first value(Click) only. That is if a word doesn't contains space then no need of Quotation.