Cleanest way to create html & xml content in angularjs - javascript

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.

Related

How to convert string into html format using ejs in 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%>');

How to prevent SQL injection in emojionearea content?

Hello guys please help me on sanitization the emojionearea content to prevent SQL injection.
I have tried using $("#id").data("emojioneArea").getText(); as to get the content on the input without it rendering the HTML tags but it still interprets the html tags such as:
<script>alert("Hi, I am interpreted")</script>
My code looks like this:
HTML
<input type="text" id="text_t">
JQuery
var textContent = $("#text_t").data("emojioneArea").getText();
I want to prevent SQL Injection here that no html tags is rendered. But the about getText() function still gets the content that renders the html tags
You can encode the < and > tags on the client side with a simple regex if you're to prevent users to input html tags.
html = html.replace(/</g, "<").replace(/>/g, ">");

Access DOM of an imported local HTML file

I'm working on a project in which I would like to import a locally stored HTML template using JavaScript.
This template will be dynamically filled with datas that I get by accessing a website REST API.
This is an example of what I want to do :
index.html :
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
</head>
<body>
<div id="loaded-content">
<!-- Here will be displayed the template -->
</div>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
template.html:
<div id="data">
<h1 id="data-name">value</h1>
<p id="first-attribute">value</p>
<p id="first-attribute">value</p>
<p id="first-attribute">value</p>
</div>
datas.json:
{
"datas":
[
{
"name": "value",
"first-attribute": "value",
"second-attribute": "value",
"third-attribute": "value"
},
{
"name": "value",
"first-attribute": "value",
"second-attribute": "value",
"third-attribute": "value"
}
]
}
For each object contained in datas, I want to display the template again.
Currently, I load the template using XMLHttpRequest object. I can display the content of my template but I can't access to the template's DOM to change the value of its elements.
Which method should I use to correctly load my HTML file ?
I'm looking for something in pure Javascript (no jQuery or something).
Thank you for your help =)
Your immediate problem is that your template as it currently stands will result in multiple elements with the same ID, which isn't allowed.
If you have control of the template, change it to be a more traditional template style where vars are bracketed off rather than relying on HTML IDs. So I'd change your template to be:
<div>
<h1>{{name}}</h1>
<p>{{first-attribute}}</p>
<p>{{second-attribute}}</p>
<p>{{third-attribute}}</p>
</div>
This way we can run string replacements via REGEX rather than outputting then interrogating the items by IDs.
Let's say #content is the container element for the templates, data stores your parsed JSON data and template stores the unparsed template string:
var
cntr = document.querySelector('#content'),
html;
//iterate over data items
data.datas.forEach(function(obj) {
//grab all var references i.e. {{foo}} and replace them with actual values, if exist
html = template.replace(/\{\{[^\}]+\}\}/g, function(match) {
var var_name = match.replace(/^\{\{|\}\}$/g, '');
return obj[var_name] || '??';
});
//append the readied HTML to the content container
cntr.innerHTML += html;
});
This is an example. You can use a JSON parser to get the data in the format you need. So here is what you do: create a dummy <div> DOM element to push later, use replace function to replace val with the value of the data variable. Then finally append this to the HTML's div element. If you got the data using an XMLHttpRequest, pass on the data to template. Then replace the placeholders value with the data from parsing JSON. And use replace method to do so. It should work fine.
var template = document.createElement("div");
var data = "Hello world";
template.innerHTML = "<h1>val</h1>";
template.innerHTML = template.innerHTML.replace("val", data);
document.getElementById("myDiv").appendChild(template);
<div id="myDiv">
</div>

Append HTML to HTML string in jQuery

I have a HTML string and I want to append another html string to this in some arbitrary location.
Example:
var htmlString = '<div id="insert"> <p> Hello </p> </div>'
var appendString = '<p> Goodbye </p>'
$(appendString).appendTo( $(htmlString).find('#insert') )
Obviously that doesn't work because it cannot insert directly into the string however, I do not want to convert htmlString into a jQuery object because it messes up the structure of the HTML document and I need the script tags to remain in the locations they have been inserted.
Hope that's clear enough.
EDIT:
My apologies, I think I explained my problem poorly.
I have a HTML string that includes a table and I want to append a new row to the table. My problem is that I have a number of <script> tags that I need to remain in their locations. When I convert the string into a $(string), I am then unable to return it to its original form:
var htmlString = $('body').html();
var $htmlString = $(x);
console.log($htmlString.html());
This is a Confluence page that I attempting to do this on and I have limited access to the source; most I can do is to modify what is already there.
The HTML string comes from a AJAX request of another page on Confluence and I need the scripts to remain in the same place so that my other macros will run correctly.
I have included a JS Bin example of my problem to hopefully illustrate my problem clearly.
https://jsbin.com/ruwawuzica/edit?html,js,output
You can do it like this:
var htmlString = '<div id="insert"> <p> Hello </p> </div>';
var appendString = '<p> Goodbye </p>';
var added = ($(htmlString).append($(appendString)));
$(added).appendTo('div');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
Since $(htmlString) is the element <div id="insert"></div> wrapped in jquery
Hi #MyLittleDax i guess you can do this:
var htmlString = "<div id='insert'> <p> Hello </p> </div>";
var appendString = "<p> Goodbye </p>";
//your container where you put the html
var container = $('#container');
container.empty();
container.append(htmlString);
var insert = $('#insert');
insert.append(appendString);
good luck!!!

html template in jquery or javascript

This is a very short example, but I was wondering if there is a way of using an xml or html file with html markup instead of including it in the javascript like I do below.
I know there are template libraries out there, but I really just want to do something simple and not involve any libraries other than jQuery.
var description = this.name;
if description == 'full') {
return "<div><textarea cols='50' rows='50'>" + this.value + "</textarea></div>";
} else {
return "<div><textarea cols='50' rows='15'>" + this.value + "</textarea></div>";
};
Thanks
In general, without a template engine you have three options:
a) Adding the template directly into your markup as script tag
<script type="text/template" data-template="stats">
<div id="content">
...
</div>
</script>
The html code inside the script tag could be accessed with the following code:
$("script[data-template=" + templateName + "]").html()
The big benefit of this approach is that you are not making another http request.
b) Putting the template in external file and load it via ajax.
$.ajax({
url: "test.html"
}).done(function(html) {
...
});
c) Doing the things like you already did.
If you use AJAX to call a file, you can use the result of the file, which could be XML or nested HTML, etc etc.
I define a hidden div on my markup - then give it a generic ID, then in javascript I use the jQuery.clone() method to make a clone of that markup, and in the markup I define the template macro values that can then be injected with the real data using .replace..
HTML:
<div id="mytemplate">
Name: {0}
</div>
JS/jQuery:
var clone = $('#mytemplate').clone();
Then perform the replacements on the clone object and simply append to the DOM where desired!

Categories

Resources