I would like to append Html as a child to a Element, i tried:
$.each(data, function(i, field){
var tbody = document.getElementsByTagName('tbody')[0];
tbody.appendChild('<tr><td>'+ field.name +'</td><td>' + field.vorname + '</td><td>' + field.geburtsdatum + '</td><td>' + field.strasse + '</td><td>' + field.plz + '</td></tr>');
});
But somehow i get this error:
Uncaught NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.
How can i fix this problem? Thanks
appendChild() takes a node as the argument, try jQuery's append() instead
var $tbody = $('tbody').eq(0);
$.each(data, function (i, field) {
$tbody.append('<tr><td>' + field.name + '</td><td>' + field.vorname + '</td><td>' + field.geburtsdatum + '</td><td>' + field.strasse + '</td><td>' + field.plz + '</td></tr>');
});
As Json said, it is best to create the html first then append it, so try
var array = $.map(data, function (field, i) {
return '<tr><td>' + field.name + '</td><td>' + field.vorname + '</td><td>' + field.geburtsdatum + '</td><td>' + field.strasse + '</td><td>' + field.plz + '</td></tr>';
});
$('tbody').eq(0).append(array.join(''));
Related
Below you see a ajax call that gets triggered when I press a button. Inside of the ajax call I append some'td' with value's to a table. On this line below: '</td><td>' + result[i].preRiskCategory + I'm trying to set the background color to a certain color when the value of preRiskCategory is above a certain number. Does anyone know if this is even possible and if so, how?
document.getElementById("searchButton").addEventListener("click", function (e) {
// vorige resultaten leegmaken.
clearTable();
if (id != "") {
$.post("/mainRiskanalysis/SearchMainRiskanalysisRisks?mainRiskanalysisId=" + id, function (result) {
for (let i = 0; i < result.length; i++) {
// Get risk-actionplan ids
getRiskActionplanIds(result[i].id);
// Looping through all ids and placing it in a string
for (j = 0; j < ids.length; j++)
idsString+=ids[j] + ", ";
//Get the names by id's
getZoneNameById(result[i].zoneId);
getEquipmentNameById(result[i].equipmentId);
getEquipmentTaskNameById(result[i].taskId);
getDangerNameById(result[i].dangerId);
getDangererousEnergieNameById(result[i].dangerousEnergiesId)
getConsequenceNameById(result[i].consequenceId);
// Getting the right table
var tbodyId = getTableId(result[i].categoryId);
$(tbodyId).append(
'<tr scope="row"><td><a class="text-primary" href="/riskanalysis/edit/' + result[i].id + '">Edit</a> | <a class="text-danger" href="/riskanalysis/delete/' + result[i].id + '">Delete</a>' +
'</td><td><a class="text-success" href="/riskActionPlan/create/' + result[i].id + '">Link actionplan</a>' +
'</td><td>' + idsString +
'</td><td style = "background-color: #C0C0C0">' + result[i].id +
'</td><td>' + zoneName +
'</td><td>' + equipmentName +
'</td><td>' + taskName +
'</td><td>' + result[i].activity +
'</td><td>' + result[i].action +
'</td><td>' + result[i].descriptionPotentialRisk +
'</td><td style="background-color: #99CC00">' + dangerName +
'</td><td>' + consequenceName +
'</td><td>' + dangerousEnergieName +
'</td><td style="background-color: #C0C0C0">' + result[i].preSeriousness +
'</td><td style="background-color: #C0C0C0">' + result[i].preProbability +
'</td><td style="background-color: #C0C0C0">' + result[i].preExposure +
'</td><td style="background-color: #C0C0C0">' + result[i].preRiskDegree +
'</td><td>' + result[i].preRiskCategory +
'</td><td>' + result[i].preventionMeasures +
'</td><td>' + result[i].safetyProcedures +
'</td><td>' + checkIfNull(result[i].postSeriousness) +
'</td><td>' + checkIfNull(result[i].postProbability) +
'</td><td>' + checkIfNull(result[i].postExposure) +
'</td><td>' + checkIfNull(result[i].postRiskDegree) +
'</td><td>' + checkIfNull(result[i].postRiskCategory) +
'</td><td>' + checkIfNull(result[i].improvementFactor) +
'</td><td>' + result[i].isOk +
'</td></tr>');
}
});
}
e.preventDefault()
});
Please let me know if you need further explaination of some sort.
Thanks!
Consider something like this:
'</td><td style="background-color: #C0C0C0">' + result[i].preRiskDegree +
'</td><td style="'+(
result[i].preRiskCategory > 100 ? 'background-color: orange;' : ''
)+'">' + result[i].preRiskCategory +
'</td><td>' + result[i].preventionMeasures +
You can concatenate a string that is either a background-color or an empty style using a ternary condition. Whitespace added for clarity.
I use a tag onclick function to delete specific documents.
I call the function with three arguments.
but my regex does not include a specific case.
Generally, it works, like "test".
but some case doen't work.
Like this case => "St. John's"
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item);
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + "\"" + value + "\"" + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
});
this is expected key value example
const key = "en";
const value = "test"; // it works
const value = "St. John's"; // it doesn't work.
const regionCode = "AG-ANU";
if onclick function call success,
it calls this function
function deleteName(key, value, regionCode) {
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + key + "&name=" + value,
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
I need help for value part regex expression.
It is not good way, but I solved like this.
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item)[0];
var valueStr = JSON.stringify(value);
var valueString = value.replace(/'/gi, "\\\'");
var keyValueRegionCode = key + "|" + valueString + "|" + regionCode;
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '[ 삭제 ]' + '</td></tr>';
});
then calls keyValueRegionCode
function deleteName(keyValueRegionCode) {
var keyValue = keyValueRegionCode.split("|")[0];
var nameValue = keyValueRegionCode.split("|")[1];
var regionCode = keyValueRegionCode.split("|")[2];
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + keyValue + "&name=" + encodeURIComponent(nameValue),
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
1) value.replace(/'/gi, "\\'"); -> this regex makes single apostrophe like this. (\')
2) make parameters one for calling function easily .
I am looping over a response that I got from an ajax response, the response is an array containing 1000 objects , this response is used to created an html table with 1000 rows :
1st scenario :
for (var i in msg.myObjects) {
$('#mytablebody').append('<tr><td>' + msg.myObjects['item1'] + '</td><td>' +
msg.myObjects['item2'] + '</td><td>' + msg.myObjects['item3'] + '</td><td>' +
msg.myObjects['item4'] + '</td><td>' + msg.myObjects['item5'] + '</td><td>' +
msg.myObjects['item6'] + '</td><td>' + msg.myObjects['item7'] + '</td> .... </tr>');
}
Result => memory leak my RAM went to 2Go and my browser crashed
2nd scenario :
for (var i in msg.myObjects) {
document.getElementById('mytablebody').innerHTML = document.getElementById('mytablebody').innerHTML + '<tr><td>' +
msg.myObjects['item1'] + '</td><td>' +
msg.myObjects['item2'] + '</td><td>' + msg.myObjects['item3'] + '</td><td>' +
msg.myObjects['item4'] + '</td><td>' + msg.myObjects['item5'] + '</td><td>' +
msg.myObjects['item6'] + '</td><td>' + msg.myObjects['item7'] + '</td> .... </tr>';
}
Result => memory leak my RAM went to 800Mo and my browser crashed with a second ajax call
3rd scenario :
var stringResponse = '';
for (var i in msg.myObjects) {
stringResponse += '<tr><td>' + msg.myObjects['item1'] + '</td><td>' +
msg.myObjects['item2'] + '</td><td>' + msg.myObjects['item3'] + '</td><td>' +
msg.myObjects['item4'] + '</td><td>' + msg.myObjects['item5'] + '</td><td>' +
msg.myObjects['item6'] + '</td><td>' + msg.myObjects['item7'] + '</td> .... </tr>';
}
document.getElementById('mytablebody').innerHTML = stringResponse
Result => no memory leak
Ok until here I concluded that, first of all, .append() causes memory leaks, and second of all , you should never play with DOM elements inside a loop. But when I did the 4th scenario I concluded that the first conclusion was wrong (not exactly correct) and the second one is still correct.
4th scenario :
var stringResponse = '';
for (var i in msg.myObjects) {
stringResponse += '<tr><td>' + replaceNulls(msg.myObjects['item1']) + '</td><td>' +
msg.myObjects['item2'] + '</td><td>' + msg.myObjects['item3'] + '</td><td>' +
msg.myObjects['item4'] + '</td><td>' + msg.myObjects['item5'] + '</td><td>' +
msg.myObjects['item6'] + '</td><td>' + msg.myObjects['item7'] + '</td> .... </tr>';
}
document.getElementById('mytablebody').innerHTML = stringResponse
function replaceNulls(input) {
return input != null ? input : ''
}
Result => memory leak my RAM went to 2Go and my browser crashed
My questions are:
when we call functions that occurs outside a loop , it may causes a memory leak, why ?
How can I avoid this (without removing the function or moving its processing to inside the loop) ?
1000 table entries for modern web browsers should not cause any issue.
Here I'm adding 10,000 items into a table without ram problems.
The reason why it's fast is because I build up the list inside a detached DOM element, then attach when done.
Your problem might be just down to DOM draw issue, the browser having to redraw on all your updates.
Another thing I noticed, for (var i in msg.myObjects) depending on what your msg.myObjects contains this is not a good thing to use. If you can use modern JS,. for (const i of msg.myObjects) is better.
var table = document.querySelector("table");
var tbody = document.createElement("tbody");
function addLine (txt) {
var tr = document.createElement("tr");
var td = document.createElement("td");
tr.appendChild(td);
td.innerText = txt;
tbody.appendChild(tr);
}
for (var l = 1; l <= 10000; l += 1) {
addLine("This is Line " + l + ", and some extra text");
}
table.appendChild(tbody);
<table>
<thead><tr><th>Test</th></tr></thead>
</table>
I am getting a users details from a MongoDB database like this:
$user=$collection->findOne(array('_id' => new MongoId($_SESSION['user']['userid'])));
if (!empty($user)){
json_encode($user);
print_r($user);
}
I can get an entire JSON array from the AJAX but not individual elements - I get undefined:
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(msg){
alert(msg);
}
});
The actual JSON is structured like this:
username: john
password: hello
email: me#mailserver.com
I'm stuck.
you returning array object from getUser.php but you display it as a normal variable
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(msg){
$.each(msg,function(key,value){
alert(value.id);
});
}
});
i guess this will work..
You need to get the return value
$encoded = json_encode($user);
print_r($encoded);
The method you are using does not encode in place. It returns a left side value.
success: function (response)
{
if(response != 'error')
{
//parse into JSON
var jsonObj = JSON.parse(response);
var HTML = '';
//extract single value using each
$.each(jsonObj, function(key, val) {
HTML += '<tr><td>' + val.id + '</td><td>' + val.first_name + '</td><td>' + val.last_name + '</td><td>' + val.gender + '</td>'
+'<td>' + dt + '</td><td>' + val.phone + '</td><td>' + val.mobile + '</td><td>' + val.email + '</td>'
+'<td>' + val.address + ',' + val.city + ',' + val.state + '</td><td>' + val.country + '</td>'
+'<td>' + val.zip + '</td><td>' + val.hobbies + '</td><td>' + 'INR ' +val.salary + '</td><td>' + val.countryCode + '</td>'
+'<td>' + val.username + '</td><td>' + val.pwd + '</td></tr>';
});
There seems to be a syntax error that I can't seem to solve in JavaScript.
var newRow = jQuery('<tr><td><div align="center"><input type="checkbox"class="case" onclick="showhide('display','')"/></div></td><td>' + daterecorded + '</td><td>' + arrivaltime + '</td><td>' + departuretime + '</td><td>9h 30min</td><td>' + specialreason + '</td></tr>');
jQuery('table.manual').append(newRow);
});
This part: onclick="showhide('display','')" has been giving me syntax errors.
I have tried this onclick="showhide(' + display + ' ' + ,''+ ')"
and get myself confused. couldn't seem to get the syntax right. any help please?
var newRow = jQuery('<tr><td><div align="center"><input type="checkbox" class="case" onclick="showhide(\'display\',\'\')"/></div></td><td>' + daterecorded + '</td><td>' + arrivaltime + '</td><td>' + departuretime + '</td><td>9h 30min</td><td>' + specialreason + '</td></tr>');
jQuery('table.manual').append(newRow);
});
You just need to escape the two ' around display.
or you can bind event after creating row
var newRow = jQuery('<tr><td><div align="center"><input type="checkbox" class="case" /></div></td><td>' + daterecorded + '</td><td>' + arrivaltime + '</td><td>' + departuretime + '</td><td>9h 30min</td><td>' + specialreason + '</td></tr>');
jQuery('table.manual').append(newRow);
newRow.find(".case").click(function () { showHide('display', ''); });
});
dont have to mind escaping and much better to read.