Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

240
Visualizações
How do I make a button that, when clicked, displays data in node.js?

So I've created a button, along with a table that shows data from my database. However, I want that data to appear only when the button is clicked. So when the button is clicked, I want a random row from a specific table I have in my database appear. enter image description here

`<button id="breakfast2">Breakfast</button>
 <table id="mealTableContainer2">
            <thead>
                <tr>
                    <th id="mealname">Meal Name</th>
                    <th id="mealcalories">Calories</th>
                    <th id="mealtype">Type of Meal</th>
                    
                </tr>
            </thead>

            <tbody id="mealContainer2"></tbody>
  </table>`

The only Javascript I currently have is for getting my database into that table, but I really only want it to appear when I click the breakfast button. I just can't figure out how; if someone could explain it to me very simply, I'd be appreciate it a ton!

console.log('Data2 received')
$.ajax({
    url: 'http://localhost:5000' + "/read-recordsrandom",
    type: 'get',
    success: function(response) {
        var data2 = JSON.parse(response);
        if(data2.msg === "SUCCESS"){
            console.log(data2.meal)
            createMealTable2(data2.meal);
        } else {
            console.log(data2.msg);
        }
    },
    error: function(err){
        alert(err);
    }

});

}

function createMealTable2(data2) { 
var tableHTML2 = " ";
console.log("Test");
for(var i=0; i < data2.length; i++){
    tableHTML2 += "<tr>";
    tableHTML2 += "<td>" + data2[i].mealname + "</td>";
    tableHTML2 += "<td>" + data2[i].mealcalories + "</td>"
    tableHTML2 += "<td>" + data2[i].mealtype + "</td>";
    
    
    tableHTML2 += "</tr>";
}

$('#mealContainer2').html(tableHTML2);   

}

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Hide it initially then display it

document.getElementById("breakfast2")
  .addEventListener('click', function(event) {
    document.getElementById("mealTableContainer2").classList.remove('hidden');
  });
.hidden {
  display: none;
}
<button id="breakfast2">Breakfast</button>
<table id="mealTableContainer2" class="hidden">
  <thead>
    <tr>
      <th id="mealname">Meal Name</th>
      <th id="mealcalories">Calories</th>
      <th id="mealtype">Type of Meal</th>
    </tr>
  </thead>
  <tbody id="mealContainer2"></tbody>
</table>

about 4 years ago · Juan Pablo Isaza Relatório

0

If I'm right, by default, the table is supposed to be hide. So you can first of all, hide the table with css

Change this line to hide the table

<table id="mealTableContainer2" style="display: none;">

After that, you will need to add event listener on the button "breakfast" in javascript to display the table on click

document.getElementById("breakfast2").addEventListener("click", function() {
    document.getElementById("mealTableContainer2").style.display = "block";
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Here is how you can ajax on click

NOTE: the `` are backticks used in template literal delimites and MUST be backticks

$(function() {
  const createMealTable2 = data => {
    $('#mealContainer2')
      .html(data.map(meal => `<tr>
          <td>${meal.mealname}</td>
          <td>${meal.mealcalories}</td>
          <td>${meal.mealtype}</td>
        </tr>`)
        .join("")  
      )
  };

  $("#breakfast2").on("click", function() {
    $.ajax({
      url: 'http://localhost:5000' + "/read-recordsrandom",
      type: 'get',
      success: function(response) {
        var data2 = JSON.parse(response);
        if (data2.msg === "SUCCESS") {
          createMealTable2(data2.meal);
        } else {
          console.log(data2.msg);
        }
      },
      error: function(err) {
        alert(err);
      }
    });
  })
})
<button type="button" id="breakfast2">Breakfast</button>
<table id="mealTableContainer2">
  <thead>
    <tr>
      <th id="mealname">Meal Name</th>
      <th id="mealcalories">Calories</th>
      <th id="mealtype">Type of Meal</th>
    </tr>
  </thead>
  <tbody id="mealContainer2"></tbody>
</table>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda