I do the following ajax query:
$.ajax({
url: '',
type: 'GET',
data: '',
success: function(response){
if (response == 1){
nom= [];
}
else{
nom = JSON.parse(response)
// console.log('Esto es la respuesta :'+nom)
for (var p = 0; p<nom.length; p++){
// console.log(nom[p].nombre)
text = nom[p].nombre
console.log(text)
$('#textoP').html(text)
}
}
}
});
It returns me two names, which I want to insert into the temporary table as rows and display their data. So I want the table to generate as many rows as there are names in this case, it only generates the first name:
fila2 += '<th id="textoP" style=" font-size: 0.9em;text-align: center;border: 1px solid #dddddd;"></th>'
Your problem is in this line:
$('#textoP').html(text)
of the code. When usinghtml()
you replace the content of the element each time, as the documentation says :Consider using
append()
which, as the documentation says :optimization
When you are going to modify something in the DOM you must not forget that it is rendered every time you modify it , that is why it is never convenient to modify the DOM inside a loop. Build a chain and do
append
once, outside the loop :In case you need to modify several parts of the DOM, you should use
DocumentFragment
.On the other hand, if you're trying to create a cell for each name, you should do
append
in an elementtr
, not an element,th
and surround each value inside the loop withth
.Let's look at an example: