How to convert string into html format using ejs in javascript - javascript

The scenario is the user will enter the text in HTML format (e.g. <\/b>Testing<\/b>) then the inserted text will get saved into the database(HTML code as a string (e.g. <\b>Testing<\/b>).
I want the string fetched back from the database to be displayed as HTML text (e.g. Testing).
I followed the below snippet but didn't get anything as output.
Note: <%= cData.description %> worked fine when executed simply but displayed HTML code as plain text.
test.js (route file):
var testid = 234123;
b.find(testid, function(data) {
b.otherdet(testid, function(cdata){
res.render('blogdesc',{
Data: data,
cdata: cdata
});
});
});
test.ejs file:
<p class="" id="descid"></p>
<script>
var $log = $( "#descid" );
html = $.parseHTML('<%= cData.description %>'); //description is column in database
$log.append( html );
</script>

https://stackoverflow.com/a/8125053/20394 shows how to emit HTML as-is in EJS, but please make sure that you sanitize that content to avoid XSS.

I've found, where did it go wrong. I was using:
html = $.parseHTML('<%=blogData.description%>');
while the actual syntax should be this:
html = $.parseHTML('<%-blogData.description%>');

Related

Passing HTML value to embedded script

So I have a HTML file with an embedded script. A Java application sends a value to this HTML file. Now I wonder how to pass this value from the HTML down to the script. Is this even possible?
Here is the simplified HTML file with my approach:
<html>
<body>
<div id="test">
[VALUE_FROM_BACKEND] // prints "let valueFromBackend = 1234"
</div>
<script>
console.log(document.getElementById('test').value);
// should return: let valueFromBackend = 1234;
// actually returns: undefined
</script>
</body>
</html>
Unfortunately, I can't pass the value from the Java application directly to the script. I got the above approach from here, but this doesn't work.
Other solutions only focus on getting values from remote HTML pages, declaring the HTML files's source in the script tag. But since it is an embedded script here, this also seems not to work.
Does anyone know how to deal with the situation? Help will be much appreciated.
Only HTML input elements have a value in javascript. A div cannot have a value, which is why your code returns undefined.
To access the text inside a regular HTML element, such as a div, use element.innerText instead.
Here is a working code snippet you can try out:
console.log(document.getElementById('test').innerText);
<div id="test">
let valueFromBackend = 1234
</div>
As you want to get value of a div element, so the syntax is:
document.getElementById('test').innerHTML
Remember that getElementById().value works for input and use getElementById().innerHTML for elements like div

How to achieve string interpolation while appending html inside a div using Javascript

Might be a silly question but here it is.
I am trying to insert some html inside my div based on data received from my backing java controller. It all works fine but I am not aware how to interpolate strings from the data I receive into the paragraph tag of my jsp.
Here is the code
<script>
$(document).ready(function() {
var url = "${context}/support/ajax";
$.ajax({
type : 'GET',
url : url,
dataType : 'json',
success : function(data, status, xhr) {
data.forEach(function(data) {
if (data.userType == 'O') {
$( ".chats" ).append(`
<div class='chat-avatar'>
<a class='avatar' data-toggle='tooltip' href='#'
data-placement='right' title='' data-original-title=''> <img
src='<c:url value = '/app-assets/images/portrait/small/avatar-s-1.png'/>'
alt='avatar'>
</a>
</div>
<div class='chat-body'>
<div class='chat-content'>
<p>{data.comment}</p> // **This is what I want to achieve**
</div>
</div>
`);
}
});
}
});
});
</script>
The above ajax call works fine an I do receive data. Also, I am able to insert this html into the appropriate div element. Now I want to insert the data.comment value inside the p element .
How do I do this ?
EDIT --1
After using `${expression}` syntax, the <p> tag comes as blank in the broswer console while clearly the value is present.
EDIT--2
I don't know why but "<p>"+d.comment+"</p>" is working. But not interpolation.
Because you are using the back-tick (`) you are close to using template strings. You just need to use placeholders correctly:
const data = {comment: 'The comment'};
const result = `...<p>${ data.comment }</p>...`;
console.log(result);
Documentation on Template Strings
I can see you're using the data variable for both the ajax response and the current value of data in the loop. Are you sure you're referencing the correct object?

Escaping quotes and tags to pass data in JS function

I have a table in which I am saving blog body data, the data is gone through TINYMCE editor and it saves tags and styling. When I am fetching the data for editing purpose and passing it through the function to open a modal it shows the tags and everything and outputting the data in button.
Here is the code:
<td>
<a class="btn btn-primary btn-md"
onclick="getData('<?php echo $blog->title?>','<?php echo
$blog->body?>',
<?php echo $blog->id?>')">Update</a>
</td>
This is the getData function
function getData(title,body,id) {
debugger;
document.getElementById('title1').value = title;
tinymce.get('body').setContent(body);
document.getElementById('blog_id').value = id;
$('#myModalUpdate').modal('show');
};
This is how it outputs on the page
enter image description here
You just need to think about each layer one at a time.
First you have some data…
$blog->title
… and you want to put it into JavaScript. So you have to escape it to make it safe for JavaScript. json_encode will do this because JSON is a subset of JS. Since you are putting a string in, you get a JSON string literal out, so you mustn't add the quotes manually.
$js_safe_title = json_encode($blog->title);
$js_safe_body = json_encode($blog->body);
$js = "getData($js_safe_title, $js_safe_body);"
… and then you want to put that JS into an HTML attribute, so you have to escape it to make it safe for HTML:
$html_safe_js = htmlspecialchars($js);
Then you can put it in the HTML:
onclick="<?=$html_safe_js?>"

Cleanest way to create html & xml content in angularjs

I need to send HTML string inside XML to a POST REST service.
Currently I am using string concatenation to create XML's and HTML's like the following,
var html = " <div style='some style'>... append model data from the response of some services ... </div> ";
html += " <div> ... append model data from the response of some services ...</div> ";
var xml = "<?xml version='1.0' encoding='utf-8'?>";
xml += "<root><data>";
xml += "<![CDATA["+ html +"]]>";
xml += "</data></root>";
return $http.post(url,xml,{headers : {'Content-Type': 'application/atom+xml'}});
It looks really ugly as the real html content is huge. Which is the cleanest way to achieve this except string concatenation?
You can do following:
Put your html code in body tag under any specific tag like div with some id or class (I have used id)
example:
The content of the document......
... append model data from the response of some services ...
... append model data from the response of some services ...
Now in javascript you can do like below:
var html = document.getElementById("parent_div").innerHTML;
alert(html);
using above code you can use your html without writing it in JS code.
Also, you can hide this if you don't want to show it on your page.

Showing text from resources.resx in JavaScript

This is example code in ASP.NET MVC 3 Razor:
#section header
{
<script type="text/javascript">
$(function() {
alert('#Resources.ExampleCompany');
});
</script>
}
<div>
<h1>#Resources.ExampleCompany</h1>
</div>
The code above this is just an example, but it also shows my problem with encoding. This variable #Resources.ExampleCompany is a file resources.resx with value ExampleCompany = "Twoja firma / Twój biznes"
In JavaScript, the alert shows the "Twoja firma / Twój biznes".
Why is character 'ó' '&#243'? What am I doing wrong?
In HTML tag, <h1>#Resources.ExampleCompany</h1> is displayed correctly.
UPDATE:
Mark Schultheiss wrote a good hint and my "ugly solution" is:
var companySample = "#Resources.ExampleCompany";
$('#temp').append(companySample);
alert($('#temp').text());
Now the character is ó and looks good, but this is still not answer to my issue.
According to HTML Encoding Strings - ASP.NET Web Forms VS Razor View Engine, the # syntax automatically HTML encodes and the solution is to use the Raw extension-method (e.g., #Html.Raw(Resources.ExampleCompany)) to decode the HTML. Try that and let us know if that works.
Some of this depends upon WHAT you do with the text.
For example, using the tags:
<div id='result'>empty</div>
<div id='other'>other</div>
And code (since you are using jQuery):
var whatitis="Twoja firma / Twój biznes";
var whatitisnow = unescape(whatitis);
alert(whatitis);
alert(whatitisnow);
$('#result').append(whatitis+" changed to:"+whatitisnow);
$('#other').text(whatitis+" changed to:"+whatitisnow);
In the browser, the "result" tag shows both correctly (as you desire) whereas the "other" shows it with the escaped character. And BOTH alerts show it with the escaped character.
See here for example: http://jsfiddle.net/MarkSchultheiss/uJtw3/.
I use following trick:
<script type="text/javascript">
$('<div/>').html("#Resources.ExampleCompany").text();
</script>
Maybe it will help.
UPDATE
I have tested this behavior of Razor more thoroughly and I've found that:
1.When the text is put as normal content of html then #Html.Raw method simply helps and writes char 'ó' without html encoding (not as: ó)
example:
<div> #Html.Raw("ó") </div>
example:
<script type="text/javascript">
var a = $('<div/>').html('#("ó")').text();// or var a = '#Html.Raw("ó")';
console.log(a); // it shows: ó
</script>
2.But if it is put inside html tags as attribute then Razor converts it to: ó and #Html.Raw doesn't help at all
example:
<meta name="description" content="#("ó")" />
Yo can fix it by putting the entire tag to Resource (as in that post) or to string (as in my example)
#("<meta name="description" content="ó" />")
So, sometimes somebody could have been little confused that the answers helps the others but not him.
I had similar issue, but in my case I was assigning a value from Resource to javascript variable. There was the same problem with letter ó encoding. Afterwards this variable was binded to a html object (precisely speaking by knockout binding). In my situation below code give a trick:
var label = '#Html.Raw(Resource.ResourceName)';

Categories

Resources