Home > Enterprise >  Live update results from database wih every charachter the user types in the search bar
Live update results from database wih every charachter the user types in the search bar

Time:01-07

I want to live update a table f results based on the charachters the user type in the search-bar

This is my search.ejs

<div >
    <form action="/search" method="post">
      <div >
        <input id="search-bar" type="text"  id="name" placeholder="name" name="name" required>
        <label for="name">name</label>
      </div>
      <button type="submit" >Search</button>
    </form>
  </div>
  <table >
    <thead>
      <tr>
        <th scope="col">First name </th>
        <th scope="col">Last name</th>
        <th scope="col">Number</th>
        <th scope="col">Date</th>
      </tr>
    </thead>
    <tbody> 
      <% array.forEach(item => { %>       
        <th><%= item.firstname %> </th>
        <th><%= item.lastname %> </th>
        <th><%= item.number %> </th>
        <th><%= item.date %> </th>
      <% }) %>
    </tbody>
  </table> 

This is script.js to listen to keys typed in by the user

document.getElementById('search-bar').addEventListener('keyup', function() {
  const searchTerm = this.value;
  fetch(`/search?q=${searchTerm}`)
});

This is my server.js

app.get('/search', function(req, res) {
  var title = "";
  var body = "";
  var script = "";
  var classe= "";
  var style = "";
  const q = req.query.q;
  console.log(q);
  connection.query('SELECT * FROM STUDENT WHERE firstname LIKE ?',[q "%"],function(err,data){
    if(err){
      console.log(err);
    }
    else{
      res.render('search',{style:style,classe:classe,array:data,modalTitle:title,modalBody:body,script});
    }
  });
});

Here I am querying my database for the name of students starting with the charachters typed by the user, when i log the data to the consol i get the response just like i want nad it' updated with evey key stroke, but the the array sent to the template is empty so i don't get in data to show on the table, i understand that the initial array is sent empty while rendering the page for the first time, but my question is how to render the array again to my template after getting the array from the database ?

I tried a lot but the array is always sent empty to the template

CodePudding user response:

The fetch call is returning the HTML document after it's called, but you're not actually doing anything with the response. Thus, the page will always remain the same. Instead of sending back the entire page, you should make a new route that only sends back the array of search results, and then use javascript to display the results on the page instead of using EJS (EJS is only evaluated when the page is rendered for the first-time, but for dynamic data like the results of a search you have to use javascript to manually update the DOM in the page).

  • Related