S
S
Sasha Pirogov2019-03-12 15:11:51
MySQL
Sasha Pirogov, 2019-03-12 15:11:51

How to return data from the database to html on click in NodeJS?

I will not hide it, NodeJS is a dark forest for me. There is a test base with phones in MYSQL. Initially, the page loads as it should, displays the sql query I need into the table. The problem is sorting by click. By clicking on Apple or Samsung, I want the table to be sorted by Apple or Samsung, pulling data from the database. But onclick doesn't work. I read that you need ajax and jquery for this. But I couldn't find an example anywhere. As far as I understand, an event handler is needed. How to make the server respond to events and do sorting without refreshing the page? Do not redirect each button on click to another page, where there will already be another sql query. This is the first topic I created, so if the question is crookedly described, then I'm sorry))

const express = require("express");
var mysql = require('mysql');
var ejs = require('ejs');
var fs = require('fs');

const app = express();

var con = mysql.createConnection({
  host: "localhost",
  port: "3306",
  user: "user",
  password: "user",
  database: "telephones"
});

var sql = "SELECT * FROM new_table;";
// function ShowAllSamsung() {
//     sql = "SELECT * FROM new_table where 'Samsung' = mark;";
//     conslole.log('Hi from BACKEND SERVER');
// };
// function ShowAllApple(){
//     sql = "SELECT * FROM new_table where 'Apple' = mark;";
// };

app.get("/", function(request, response) {
  fs.readFile('./index.ejs', 'utf-8', function(err, content) {
    if (err) throw err;
    console.log('Creating the http server');
    // if (ShowAllApple() == true){
    //     sql = "SELECT * FROM new_table where 'Apple' = mark;"
    // } else if (ShowAllSamsung() == true) {
    //     sql = "SELECT * FROM new_table where 'Samsung' = mark;";
    // } else {
    //     sql = "SELECT * FROM new_table;";
    // };
    con.query(sql, function(err, rows, fields) {
      if (err) throw err + console.log("NOT CONNECTED! " + err);
      console.log("Connected!");
      response.writeHead(200, {
        'Content-Type': 'text/html'
      });
      var renderedHtml = ejs.render(content, {
        rows: rows
      });
      console.log('Hello from back')
      response.end(renderedHtml);
    });
  });
});
app.listen(3000);

БД
[{"id-code":1, "mark":"Apple", "model":"5s", "color":"red", "capacity":"16gb", "price":"120$"},
 {"id":2, "mark":"Samsung", "model":"Galaxy S10", "color":"black", "capacity":"64gb", "price":"800$"},
 {"id":3, "mark":"Huawei", "model":"P20 Smart", "color":"blue", "capacity":"128gb", "price":"560$"},
 {"id":4, "mark":"Xiaomi", "model":"Mi 8", "color":"black", "capacity":"64gb", "price":"450$"},
 {"id":5, "mark":"Apple", "model":"8", "color":"white", "capacity":"128gb", "price":"750$"},
 {"id":6, "mark":"Samsung", "model":"Galaxy A9", "color":"purple", "capacity":"256gb", "price":"530$"}]

HTML
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="./style.css">
  <title>TESTTABLE EJS</title>
</head>

<body>
  <div class="container">
    <div class="tablo">
      <table>
        <tr>
          <th>id</th>
          <th>Марка</th>
          <th>Модель</th>
          <th>Цвет</th>
          <th>Обьем</th>
          <th>Цена</th>
        </tr>
        <% for(var i=0; i < rows.length; i++) { %>
          <tr>
            <td>
              <%= rows[i].id %>
            </td>
            <td>
              <%= rows[i].mark %>
            </td>
            <td>
              <%= rows[i].model %>
            </td>
            <td>
              <%= rows[i].color %>
            </td>
            <td>
              <%= rows[i].capacity %>
            </td>
            <td>
              <%= rows[i].price %>
            </td>
          </tr>
          <% } %>
      </table>
    </div>
    <!-- /.tablo -->
    <form method="POST" type="submit">
      <div class="buttons">
        <input type="button" data-name="AppleButton" value="Apple" id="AppleBtn" onclick="ShowAllApple()">
        <input type="button" value="Samsung" id="SamsungBtn" onclick="ShowAllSamsung()">
        <input type="button" value="Youtube" onclick="window.location.href='http://www.youtube.com'">
        <input type="button" id="btn" value="Google" onclick="window.location.href='http://www.google.com'">
        <input action="action" onclick="window.history.go(-1); return false;" type="button" value="Назад" />
      </div>
      <!-- /.buttons -->
    </form>
  </div>
  <!-- /.container -->
  <script type="text/javascript" src="app.js"></script>
  <script>
    // обработчик DOM-елемента
    AppleBtn.onclick = function() {
      alert('Hi from Front');
    };
  </script>

</body>

</html>

5c87a1a3970df335802072.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2019-03-12
@Kozack

In fact, you don't need ajax, nothing.
Just click on the button to sort your array and redraw the table

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question