Rows is not Iterable Error in EJS response - node.js

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

Related

How to make my update button work correctly

I am making a todolist app using express, mongoose, mongodb, bootstrap. When I hit my update button to update a task it just makes a duplicate of the task that i'm trying to update. How would I go about making my update button update the original task?
Here are some screenshots on what happens when I try to update :
https://i.stack.imgur.com/t11OG.jpg - here I created a task "make breakfast".
https://i.stack.imgur.com/ijt98.jpg - here I hit the yellow update button and I am updating the task from "make breakfast" to "make lunch".
https://i.stack.imgur.com/V4RCe.jpg - here when I hit the green update button it creates a separate task instead of updating the original "make breakfast" task.
My routes and my ejs for the home page are below:
I can also show the ejs for updating a task as well.
Thanks
const express = require("express");
const { route } = require("express/lib/application");
const router = express.Router();
const mongoose = require("mongoose");
const Todoinfo = require("../models/infoSchema");
router.get("/", async (req, res) => {
// get all todos
const allTodos = await Todoinfo.find({}).sort("-date");
res.render("home", { allTodos });
});
router.post("/", async (req, res) => {
// add a todo
const newTodo = new Todoinfo(req.body); // create a new todo
await newTodo.save((err) => {
// save the new todo
if (err) {
res.send("Not updated");
}
});
//res.redirect("/");
});
router.get("/:id/delete", async (req, res) => {
// delete a todo
const todoDelete = await Todoinfo.findByIdAndDelete(req.params.id); // find the todo by id and delete it?
res.redirect("/"); // redirect to home page
});
router.get("/:id/finish", async (req, res) => {
// finish a todo (change status to completed)
const todoDelete = await Todoinfo.findByIdAndUpdate(req.params.id, {
progress: "Completed",
});
res.redirect("/");
});
router.get("/:id/update", async (req, res) => {
// update a todo (change status to in progress)
const updateTodo = await Todoinfo.findById(req.params.id); // find the todo by id and update it?
res.render("update", { updateTodo }); // render the update page with the todo
});
router.get("/:id/update/final", async (req, res) => {
// update a todo (change status to finished)
const updateTodo = await Todoinfo.findByIdAndUpdate(req.params.id, {
// find the todo by id and update it?
description: req.body.description, // update the description of the todo with the new description
});
res.redirect("/");
});
module.exports = router;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Todo App</title>
</head>
<body>
<section class="vh-100" style="background-color: #eee ">
<div class="container py-5 h-100">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col col-lg-12 col-xl-g">
<div class="card rounded-3">
<div class="card-body p-4">
<h4 class="text-center my-3 pb-3 text-primary ">My Todo App</h4>
<form class="row row-cols-lg-auto g-3 justify-content-center
align-items-center mb-4 pb-2" action="/" method="POST">
<div class="col-12">
<div class="form-outline">
<input type="text" id="form1" class="form-control" name="description" />
<label class="form-label" for="form1">Create a new task </label>
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary mb-4">Add</button>
</div>
</form>
<table class="table mb-4">
<thead>
<tr>
<th scope="col">Item No.</th>
<th scope="col">Todo Item</th>
<th scope="col">Action</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
<% for(let i= 0; i <allTodos.length; i++) { %>
<tr>
<% let z= i + 1 %>
<th scope="row"><%= z %></th>
<% if (! allTodos[i].progress.localeCompare(" Completed" )) { %>
<td class="text-decoration-line-through"> <%=
allTodos[i].description %> </td>
<%} else {%>
<td> <%= allTodos[i].description %> </td>
<%}%>
<td> <%= allTodos[i].progress %> </td>
<td>
<button type="submit" class="btn btn-danger ms-1 mb-1">Delete</button>
<% if (! allTodos[i].progress.localeCompare(" Completed"))
{ %>
<%} else {%>
<a href="/<%= allTodos[i]._id %>/finish" class="text-decoration-none">
<button type="submit" class="btn btn-success ms-1 mb-1">Finished</button></a>
<button type="submit" class="btn btn-warning ms-1 mb-1">Update</button>
<% } %>
</td>
</tr>
<% } %>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>

ExpressJS : SQLITE_RANGE: column index out of range WHERE condition

I am working on a project using express , EJS and SQLite , So i made a function that select data from the database, and render it to the interface, this is the function:
function findHomeforSell(req , res , next){
const sell = "Sell";
db.all('SELECT * FROM home WHERE for = ? ', [
sell
] ,function(err , rows){
if (err) { return next(err);}
var homes = rows.map(function(row) {
return {
id: row.id,
location: row.Location,
four: row.for,
space: row.space,
bathrooms: row.bathrooms,
bedrooms: row.bedrooms,
price: row.price,
url: '/' + row.id
}
});
res.locals.homes = homes;
});
};
the ejs file:
<div class="house-list" id="buy">
<h1>Buy</h1>
<ul class="todo-list">
<% homes.forEach(function(home) { %>
<li>
<form action="<%= home.url %>" method="post">
<div class="view">
<table>
<thead>
<th>Location</th>
<th>For</th>
<th>Space</th>
<th>Bathroom</th>
<th>Bedroom</th>
<th>Price</th>
</thead>
<tbody>
<td><label ondblclick=""><%= home.location %> </label></td>
<td><label ondblclick=""> <%= home.four %></label></td>
<td><label ondblclick=""><%= home.space %> SQRM </label></td>
<td><label ondblclick=""> <%= home.bathrooms %></label></td>
<td><label ondblclick=""><%= home.bedrooms %> </label></td>
<td><label ondblclick="">$ <%= home.price %> SDG</label></td>
</tbody>
</table>
</div>
</li>
<% }); %>
</ul>
</div>
and the error:
SQLITE_RANGE: column index out of range
I couldn't understand the error so what to do

Updata table html EJS + Nodejs + Expressjs

I have an application nodejs + expressjs + ejs.
I am building a history search screen, my question is how to update my ejs html table with the values ​​returned in the response.
Uploading the screen with the values ​​is working, but when I enter the filters and search, I would like to update my table.
In the example below is how to use to load the html the first time with the data of the query, I would like to fill in an initial and final date and click on searching and updating the html.
EJS HTML
<div class="row">
<div class="col-md-2">
<div class="form-group">
<label for="dataPrimayID">Date Primary</label>
<input type="text" class="form-control datepickerDefault" id="dataPrimayID" name="dataPrimary" maxlength="250">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="dataFinalID">Date Final</label>
<input type="text" class="form-control datepickerDefault" id="dataFinalID" name="dataFinal" maxlength="250">
</div>
</div>
<div class="col-md-2">
<a id="btnSearch" class="btn btn-primary">Search</a>
</div>
</div>
<div class="row">
<div class="table-responsive col-md-12">
<table id="dataTableHistoricoID" class="table table-striped" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>Name</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<% if(data.length > 0){ %>
<% for ( var i = 0 ; i < data.length ; i++){ %>
<tr>
<td>
<%= data[i].name%>
</td>
<td>
<%= data[i].lastname%>
</td>
</tr>
<% } %>
<% } %>
</tbody>
</table>
</div>
</div>
ROUTER
var express = require('express');
var router = express.Router();
var historyController = require('../controllers/history-controller');
router.get('/find', historyController.findHistory);
module.exports = router;
Controller
db.query(sql, function (err, rows) {
if (err) {
var message = err.message;
console.log(message);
return res.status(500).send(message);
}else {
var data = rows;
res.render('history/search-history', {data: data});
}
});
EJS is static after compiling, you can't change it on backend-side. There are two ways of it.
Refreshing the page every time you want to render new content.
Implement client-side JS code that will handle api requests and render new elements.
For example, using Jquery:
$.post(url, (result) => {
let data = JSON.parse(result);
let innerHTML = '';
for (let item of data) {
innerHTML += `<tr>
<td>
${item.name}
</td>
<td>
${item.lastname}
</td>
</tr>`;
}
$('#dataTableHistoricoID tbody').html(innerHTML)
};

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}]]

How does routing affect form validation

I'm working on my first project in node and I'm trying to validate the a form using jQuery validation http://jqueryvalidation.org
I have it working on jsfiddle http://jsfiddle.net/o16u2fLq/ , but in my project my form is submitting without the validations. I think it has to do with how I'm routing the form, but I'm not sure what the problem is.
Here are my routes:
var express = require('express');
var router = express.Router();
var Greeting = require('../models/greetings');
router.get('/', function(req, res) {
Greeting.getGreetings(req).then(function (greetings) {
res.render('index', { greetings: greetings });
res.redirect('/');
});
});
router.post('/greeting', function(req, res){
console.log(req.body);
Greeting.createGreeting(req, res);
res.redirect('/');
Greeting.getGreetings(req).then(function (greetings) {
res.render('index', { greetings: greetings });
});
});
module.exports = router;
I've tried playing around with the routes, but nothing was working. How am I able to validate the form before posting the submission?
Edit:
html as requested
<!DOCTYPE html>
<html>
<head>
<link href="./bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="./bower_components/jquery-ui/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="./css/custom.css">
</head>
<body>
<div class="container-fluid" style="padding-top:20px">
<form action="/greeting" method="Post" enctype="application/x-www-form-urlencoded" class="form-horizontal col-lg-4" id="welcome">
<div class="form-group">
<label for="guest" class="col-lg-3 control-label">Guest Name: </label>
<div class="col-lg-9">
<input type="text" class="form-control" id="guest" name="guest">
</div>
</div>
<div class="form-group">
<label for="message" class="col-lg-3 control-label">Message: </label>
<div class="col-lg-9">
<textarea class="form-control" id="message" name="message" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<label for="datepicker" class="col-lg-3 control-label">Date: </label>
<div class="col-lg-9">
<input type="text" class="form-control" name="display_date" id="datepicker">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-3 col-lg-9">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
<div class="col-lg-offset-2 col-lg-5">
<table class="table">
<thead>
<th>
Guest
</th>
<th>
Message
</th>
</thead>
<tbody>
<% for(var i=0; i < greetings.length; i++) { %>
<tr>
<td><%= greetings[i].guest %></td>
<td><%= greetings[i].message %></td>
</tr>
<% } %>
</tbody>
</table>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="./bower_components/jquery-ui/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.js"></script>
<script src="./scripts/custom.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</html>
in my openion
create a validator.js file
add all validations
in app.js file first you point to the valdator, after go to router folder

Resources