How to render sqlite3 data into HTML tables using {{#each}} - node.js

I am following a node.js tutorial but instead of using mongodb I am trying out sqlite. I have everything working. I am able to store data into the sqlite database but now I need to display it in an HTML table. Here's my code for retrieving data from a table called News
index: (req,res) => {
let sql = 'SELECT *'
sql += 'FROM News'
db.all(sql, [], (error, rows) => {
if (error){
console.log(error);
}
res.send(rows);
//res.redirect('admin/index');
});
},
Now I am able to send this row to the browser using
res.send(rows)
Here is my html code,
<div class="container-fluid">
<div class="alert alert-secondary text-center">
<h1>ALL POSTS</h1>
</div>
<table class="table table-bordered">
<thead class="bg-dark text-center">
<tr class="text-white">
<th>ID</th>
<th>Title</th>
<th>Content</th>
</tr>
</thead>
<tbody class="text-center">
{{#each this}}
<tr>
<td>{{id}}</td>
<td>{{title}}</td>
<td>{{content}}</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
I tried to use res.render after res.send to render the tables but it throw error
Cannot set headers after they are sent to client.
How do I do this solve this? I can see the data in my browser now I want to render it in my table.

Hi guys I figured it out. You have to render the page and send data in the same res.render(). So this is what you have to do,
//just remove the
res.send(rows);
//and replace it with
res.render('admin/index', {news:rows});
and replace with in your html/handlebars
{{#each news}}

Related

Rows is not Iterable Error in EJS response

Hello I am getting an error in my EJS response file I am trying to display my form data that makes a request to my database on the server side and I am getting this error here is the Form Code and the Server side
<body>
<form method="POST" action="/user/post">
<table>
<tr>
<td>Username</td>
<td><input type="text" name="username" ></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Save" ></td>
</tr>
</table>
</form>
</body>
<html>
<head>
<title>Message Logs</title>
</head>
<body>
<div>
<% for (var row of rows) { %>
<div><%= row.username %> <%= row.message %></div>
<% } %>
</div>
</body>
</html>
app.post('/user/post',function(req,res){
db.all(`SELECT * FROM messages WHERE name='${req.body.username}'`, (err, rows) => {
if (err) {
console.error(err.message);
}
res.render('userinfo', { rows: rows });
});
I am expecting it to display my database query it is an sqlite3 database and the table name is : messages with the fields : username , message
Found the error just a syntax mistake in the db query should have been WHERE username not where name

How to use "Flat Json"-Bootstrap 5 Table example with ejs + nodejs + expressjs

I want to use the "Flat Json"-Bootstrap 5 Table example. [Link][1]
I am using expressjs with nodejs and ejs.
My Code so far:
```<link href="https://unpkg.com/bootstrap-table#1.18.1/dist/bootstrap-table.min.css" rel="stylesheet">
<script src="https://unpkg.com/bootstrap-table#1.18.1/dist/bootstrap-table.min.js"></script>
<body>
<h2>JOB DASHBOARD</h2>
<table id="table" data-toggle="table" data-flat="true" data-search="true" >
<thead>
<tr>
<th data-field="" data-sortable="true">Order ID</th>
<th data-field="" data-sortable="true">Liefertermin</th>
<th data-field="" data-sortable="true">Fertigstellungstermin</th>
<th data-field="" data-sortable="true">Keyline Nr</th>
</tr>
</thead>
<tbody>
<% var count = 0; %>
<% orders.forEach((order)=>{ %>
<tr data-index="<%= count %>">
<td><%= order.order_id %></td>
<td><%= order.due_at %> </td>
<td><%= order.deliver_at %> </td>
<td><%= order.keyline_obj.event.data.attributes.reference %> </td>
</tr>
<% count +=1; %>
<% }) %>
</tbody>
</table>
</body>
</html>```
I am loading the content from my mongoDB Database. The Variable "orders" is an array of order documents.
At the moment the data is loading but the searchfield doesnt appear at all and all the styling doesnt work although I have loaded the bootsrap css and js.
[1]: https://examples.bootstrap-table.com/index.html?bootstrap5#welcomes/flat-json.html
i think the problem is that the is successfully sent but the respond is in json as the browser waiting
you can check data is received or not by => clicking right click on the screen =>press inspect => Network => click on the page file => then choose Response
you will find your html page with the updated data in it
you can render it from your js script after fetching api like so
await fetch(----your fetching code-----).then(res=>{
document.open();
res.text().then(function(text) {
document.write(text)
});
})

Data is not render into EJS page

I am looking for a solution for my EJS template. I am working on a project and I have completed about 50% of it. Currently I am working on a web page where I have to display the SQL data into EJS web template.
I have posted my coding which is i am working on it.
data is receiving from database (I checked with console.log and I posted the Json out put).
I tried all the possible ways to work it out but I did not get the result. It would be great if someone could help me..
Thanks in advance.
/* app.js */
app.get('/data', receiveData);
function receiveData(req, res)
{
db.executeSql("SELECT * FROM arduino", function (recordsets, err, ) {
var data = JSON.stringify(recordsets);
if (err) {
httpMsgs.show500(request, res, err);
}
else {
var Jdata = JSON.parse(data);
res.render('arduino',{Jdata:Jdata});
console.log(data);
}
});
}
/* arduino.ejs */
<html>
<head>
<body>
<div class="page-data">
<div class="data-table">
<table border="1" cellpadding="7" cellspacing="7">
<tr>
<th> - </th>
<th>ID</th>
<th>Machine</th>
<th>Start Time</th>
<th>End Time</th>
<th>Length Time</th>
<th> Day/Night</th>
<th>Job Number</th>
</tr>
<% if(Jdata.length){
for(var i = 0;i < Jdata.length;i++) { %>
<tr>
<td><%=(i+1)%></td>
<td> </td>
<td><%=Jdata[i].Machine%></td>
<td><%=Jdata[i].StartTime%></td>
<td><%=Jdata[i].EndTime%></td>
<td><%=Jdata[i].LengthTime%></td>
<td><%=Jdata[i].Day%></td>
<td><%=Jdata[i].ID %></td>
<td><%=Jdata[i].JobNumber %></td>
</tr>
<% }
}else{ %>
<tr>
<td colspan="3">No Data</td>
</tr>
<% } %>
</table>
</div>
</div>
</body>
</head>
</html>
{"recordsets":[[{"ID":1,"Machine":"TRUMPF 5000","StartTime":"2018-11-01T15:28:51.000Z","EndTime":"2018-11-01T15:52:11.000Z","LengthTime":271,"Day":"Day","JobNumber":null}]]

NotFoundHTTPException while pagination. Laravel

I'm trying to paginate my views. I have used following syntax to do that:
Route:
Route::get('Bill/view/month/history','BillController#monthHistory');
Controller:
public function monthHistory(Request $request)
{
$month= $request->month;
$bills=Bill::orderBy('created_at', 'desc')->where('month',$month)->paginate(7);
$bills->setPath('custom/url');
return view('Bill.monthResult',compact('bills'));
}
View:
<div class="row">
<div class="col-sm-12">
#section ('cotable_panel_title','Bills')
#section ('cotable_panel_body')
<table class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Student</th>
<th>Grade</th>
<th>Month</th>
<th>Date Published</th>
<th>Amount</th>
<th>Paid</th>
<th>Balance</th>
<th>User</th>
</tr>
</thead>
<tbody>
#foreach($bills as $bill)
<tr class="info">
<td>{{$bill->id}}</td>
<td>{{$bill->student->first_name}}</td>
<td>{{$bill->grade->grade_name}}</td>
<td>{{$bill->month}}</td>
<td>{{$bill->date_published}}</td>
<td>{{$bill->amount}}</td>
<td>{{$bill->paid}}</td>
<td>{{$bill->fee_status}}</td>
<td>{{$bill->user}}</td>
</tr>
#endforeach
</tbody>
</table>
#endsection
#include('widgets.panel', array('header'=>true, 'as'=>'cotable'))
</div>
</div>
</div>
{!! $bills->render() !!}
While the Pagination works fine for the first page, When i click on next page it throws not foundhttpexception with URL:
http://localhost:8000/Bill/view/month/custom/url?page=2
How can i solve this problem? Can anyone help me?
you also need to have a GET route for
Route::get('Bill/view/month/history/custom/url','BillController#monthHistory');
in your routes file.
or you can do this to
use custom url as optional variables on your route as below.
Route::get('Bill/view/month/history/{custom?}/{url?}','BillController#monthHistory');
and do use set path like this in your controller
$bills->setPath('/Bill/view/month/history/custom/url');

How can I get data from table using parent()

I try to get data from table, there is a link "Kaydet" when I click it, I must get a data from table which belong to it row, I share my table, it is like below:
https://hizliresim.com/PB3Dmv
sozlesme.js
Template.sozlesmeListele.events({
'click .kaydet': function (event, template) {
event.preventDefault();
var sozlesmeBilgileriAl = $(event.currentTarget).parent().parent().find(".secilenArac");
saveSozlesmeBilgisi = sozlesmeBilgileriAl.val();
alert(saveSozlesmeBilgisi);
}
});
sozlesmeAl.html
<tbody>
{{#each sozlesmeList}}
<tr>
<td>{{kullaniciadi}}</td>
<td>{{rezervasyonnumarasi}}</td>
<td>{{KiradaKalicakGun}}</td>
<td>{{telefon}}</td>
<td>{{alistarihi}}</td>
<td>{{iadetarihi}}</td>
<td class="secilenArac">{{secilenarac}}</td>
<td>{{aracteslimadresi}}</td>
<td>{{odenecekTutar}} TL.</td>
<td>Ceyhun TEKİN</td>
<td> Kaydet</td>
</tr>
{{/each}}
</tbody>
How can I solve it?
Deciphering Turkish Javascript is a new challenge for me but if I'm reading your question correctly, you want to figure out which row was clicked and get the data from that row, correct?
The simplest solution is to break up your template into an outer list-level one and an inner, row-level one. Then you can react to click events on the row and get your data context automatically. No need to try to figure out which row was clicked on.
Template.tekSozlesme.events({
'click .kaydet': function (event, template) {
event.preventDefault();
console.log(this); <!-- *this* will be the row data context
... do something with it
}
});
<template name="sozlesmeListele">
<tbody>
{{#each sozlesmeList}}
{{> tekSozlesme }}
{{/each}}
</tbody>
</template>
<template name="tekSozlesme">
<tr>
<td>{{kullaniciadi}}</td>
<td>{{rezervasyonnumarasi}}</td>
<td>{{KiradaKalicakGun}}</td>
<td>{{telefon}}</td>
<td>{{alistarihi}}</td>
<td>{{iadetarihi}}</td>
<td class="secilenArac">{{secilenarac}}</td>
<td>{{aracteslimadresi}}</td>
<td>{{odenecekTutar}} TL.</td>
<td>Ceyhun TEKİN</td>
<td>Kaydet</td>
</tr>
</template>

Resources