Display script data comes from database without executing it in javascript? [duplicate] - javascript

This question already has answers here:
How to display raw HTML code on an HTML page
(30 answers)
Closed 3 years ago.
I am getting myList from database and append it to my table.
$.each(myList, function (index, data) {
var row = '<tr>';
row = row
'<td class="action"><a href=\'#\' title=\'Edit Note\' onclick="showPopup(' + '\'' + note.RID + '\'); return false;" ><img width=\'25\' height=\'20\' src=\'../images/text-editor.png\' /></a></td>'
+ '</tr>';
$('#tblNotes').append(row);
});
if the value of row comes from database is a script then how to show it on my table without executing the script?
One solution is, we can remove the script tag. like this:
row = row.replace("<script>", "");
row = row.replace("</script>", "");
But I don't want it. I have to show the exact value.

I got the answer.
By using html entity, I solved this.
row = row.replace("<script>", "<script>");
row = row.replace("</script>", "</script>");
by adding these lines, I can stop executing the script.

Either will work
var row = `Here is some embedded script <script>alert('bla')<\/script>`
document.getElementById("x").innerText = row
row = row.replace(/</g, "<");
document.getElementById("y").innerHTML = row
<span id="x"></span>
<hr/>
<span id="y"></span>

Related

Get id from foreach loop javascript

After looping the delete button, I've been trying to get the id so that I can use it with the onclick function but no luck yet.
var table = "";
res.data.forEach((value, key) => {
table += "<tr>";
table += "<td>"+value.post_held+"</td>";
table += "<td>"+value.established_officer+"</td>";
table += "<td>"+value.date_of_commencement+"</td>";
table += "<td>"+value.date_of_termination+"</td>";
table += "<td><button id=career"+value.id+" class='btn btn-danger'>Delete</button></td>";
table += "</tr>";
var career = document.querySelector("#career"+value.id);
career.addEventListener("click",()=>{
alert("done")
})
});
I think maybe you forgot to add table to DOM.
You just create a string value which contain html code, but you didn't add this html code into the DOM, so you can not find this DOM element by id.
You can use insertAdjacentHTML method to add this element which you want to DOM

Javascript - img onlick() function passing arguments error [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 2 years ago.
I'm trying to pass arguments to onclick handler. The table rows are constructed dynamically in a loop and each row contains a tag with different args. Suppose there are two rows, and when clicking the first img, the argument is always the argument corresponding to the second(last) row.
JS code
for(...){
id = get_id(); // every row's id is different
img = '<img src="/img/icon-view.png" height="20" width="20" style="cursor:pointer"
onclick="view_detail(id)">'
row = ('<tr> ' + '<td>' + img + '</td>' + '</tr>')
$("#table_1").append(row)
}
function view_detail(id){
...
// the first row's id is always the second id's row
}
Comment:
Jquery passing ID from <img> to function gives a solution, but the trick here is id is a variable.
<img onclick="Myfunction(this.id)" src="files/pic/Website.png" id="Website">
Finally I found a workaround which is very simple - create img element and converts to string, and then put the string in row tag.
Sample code:
var img = document.createElement("img")
img.setAttribute("id","local_variable")
img.setAttribute("onclick","view_detail(this.id)")
var img_str = img.outerHTML(img)
row = '<tr>' + '<td>' + img_str + '</td>' + '</tr>'
Code in onXXX attributes is executed in the global scope, so it can't use captured local variables in a closure.
Nurul Huda's answer is ideal. But a simple fix to your code is to substitute the actual value of id rather than referencing the variable.
id = get_id(); // every row's id is different
img = `<img src="/img/icon-view.png" height="20" width="20" style="cursor:pointer"
onclick="view_detail(${id})">`
Dont use string to build DOM, but use document.createElement() instead. Then you can get instance of each target, add any event listeners, you can also pass those instances as arguments to other function as you want.
Here is a sample snippet you can try (I used button instead of img).
const tbody = document.querySelector('table tbody')
const btnAddRow = document.querySelector('button#btn-add-row')
btnAddRow.addEventListener('click', e => {
const row = document.createElement('tr')
const col = document.createElement('td')
const content = document.createElement('button')
content.innerHTML = `Row ${tbody.childNodes.length}`
content.addEventListener('click', e => {
alert(`${content.innerHTML} clicked!`)
})
col.append(content)
row.append(col)
tbody.append(row)
})
<button id="btn-add-row">Add row</button>
<hr>
<table border="1">
<thead>
<tr>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Another advantage is, your code becomes more readable and modern.

Need help to add javascript array contents to an existing piece of HTML code

My front-end skills are fairly limited. I have a trained language model which generates 'tweets'.
I have this javascript function which currently displays the tweets as a paragraph.
function addResponse(msg) {
document.getElementById("results").textContent = ""
var para = document.createElement("div");
var s = "<div class='center' id='gpt2'> <b> Here what our BOT has to say... </b> </br></br>"
i = 1
for (var key in msg){
var value = msg[key];
console.log(value);
s = s + i + ") " + " <b>" + value + "</b> </br></br>"
i = i + 1
}
para.innerHTML = s + "</div>";
document.getElementById('append').appendChild(para);
}
Instead of displaying in a paragraph, I want to display as a proper tweet.
Here is a tailwind CSS implementation to create the UI of the tweet: https://codepen.io/webcrunchblog/pen/xedQVv
Currently this displays a fixed string "Starhopper". What I want to do is, loop through my array object 'msg' and display all the tweets with the proper UI .
Currently the addResponse() is called as part of ajax callback for successful response. From there how can I include the tailwind CSS code so that I can display every array element in its own tweet UI?
Hope the question is clear.
EDIT: Created this codepen if anyone wants to try it out: https://codepen.io/nikhilno1/pen/RwPBWvb
In the output, there is a tweet and three sentences. I want 3 tweets to be created for each of the sentence.
I've updated a bit of your code here: https://codepen.io/rxna/pen/OJVwMOm
The idea is to:
Clone the tweet element, have added a custom class for that:
var articleNode = document.querySelector(".tweet-body");
var clone = articleNode.cloneNode(true);
Update the text within each element:
var title = clone.querySelector(".tweet-text");
title.innerText = value;
And lastly append within the DOM:
document.getElementById("append").appendChild(clone);
It's not perfect but hopefully you'd get the idea.

Making a dynamic html table on basis of php response to ajax request

I have page which send request to a php for getting some data and in response to that request of php returns me something like this:-
[{"postID":"1","0":"1","userID":"3","1":"3","imagePath":"images\/31481440272.jpg","2":"images\/3-1481440272.jpg","postDate":"11 December 2016","3":"11 December 2016","postDescription":"trying","4":":D trying"}]
What I want is to make a dynamic html table inside a specific div
<div id="dataWillBeShownHere"></div>
What will I do if records will be more than 1.Should I use for each loop for more than one record.
I am really confused in this thing. Somehow I know the solution but cannot implement.
I hope you have understand my question.
You can do this with simple javascript and html:
<script type="text/javascript">
var records = [];
// This data could be retrieved from an ajax $.post
var data = {"postID":"1","0":"1","userID":"3","1":"3","imagePath":"images\/31481440272.jpg","2":"images\/3-1481440272.jpg","postDate":"11 December 2016","3":"11 December 2016","postDescription":"trying","4":":D trying"};
// Add our data to the records array
records.push(data);
// Get how many record we have
var record_count = records.length;
// Parse data to html tables
for (var i = records.length - 1; i >= 0; i--) {
var html = "";
// make your html additions here
html += "<div> ID: " + records[i]["postID"] + "</div>";
html += "<div> Date: " + records[i]["postDate"] + "</div>";
// html += ;
// html += ;
// Now use jquery selector to write to the div
$('#data-table').html(html);
};
</script>
<div id="data-table"></div>
Check my JSFiddle

jquery - append html doesn't append the empty String inside the div

I am doing a chat project in java.
Using my Server response through jquery-ajax , I am creating an html and append the html to div.
My jquery - html alert without empty string-name(note the id='user' in the alert) will be ,
after appending this in the chat area ,
After jquery-html alert with empty string-name(note the id='user' in the alert) will be ,
after appending this in the chat area ,
My jquery for creating the HTML will be ,
function send(name , message , time){
//name = $("#name").val();
//message = $("#message").val();
var user = "<div id='user' class='fontStyle'>"+name+"</div>";
var msg = "<div id='msg' class='fontStyle'>"+message+"</div>";
var timeStamp = "<div id='time' class='fontStyle'>"+time+"</div>";
var row = "<div id='msgSet' >"+ user + msg + timeStamp +"</div>";
alert(row);
return row;
}
There is no empty string will be present in chat area.
Hope our stack members will help me.
You can escape html your string so it keeps the white spaces. See details here.
Or you can trim your message string (=remove spaces at the beginning and end of it) with such an instruction, and then manualy add the spaces (with the code inside a div, span, ...):
s.replace(/\s+/g, ' ');

Categories

Resources