How to pass url parameter to the template in express js - javascript

I have the following code in my server.js:
app.get('/animal/:id', function (request, response)
{
Animal.find({_id: request.params.id}, function(err, animals)
{
response.render('animal', { animals: animals });
})
})
I am trying to get the animal id to show up in the template url.
<table border='1'>
<tr>
<th>Name</th>
<th>Actions</th>
</tr>
<% for (var i in animals){ %>
<tr>
<td><a href='/animal/?id=**ID RIGHT HERE** %>><%= animals[i].name %></a></td>
<td><a href='#'>Edit</a> <a href='#'>Delete</a></td>
</tr>
<% } %>
</table>
If I just put in animals[i]._id, it treats as a string, but if I write it as <%= animals[i]._id %>, the whole column is removed.

use the expression, you shouldn't send this as query.
<%= animals[i]._id %> will be used as params id in your server.js and the <%= animals[i].name %> as anchor tag name
<table border='1'>
<tr>
<th>Name</th>
<th>Actions</th>
</tr>
<% for (var i in animals){ %>
<tr>
<td><a href='/animal/<%= animals[i]._id %>'><%= animals[i].name %></a></td>
<td><a href='#'>Edit</a> <a href='#'>Delete</a></td>
</tr>
<% } %>
</table>

Related

"Is not defined" error trying to read database with nodejs and ejs

I can read the database and render it in the file mascotas.ejs but can't do it in the file index.ejs, it throw an error "arrayMascotas is not defined".
For the database I'm using mongoDB, also I'm using ejs templates and express.
Sorry if I didn't explain something correctly, it's my first web using mongoDB and probably is a small thing but I've trying resolve it during hours.
The idea is to read and render the data from mongodb into a table, in mascotas.ejs is working but not in index.ejs
mascotas.ejs
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">a</th>
</tr>
</thead>
<tbody>
<% if(arrayMascotas.length > 0) { %>
<% arrayMascotas.forEach(mascota => { %>
<tr>
<th scope="row"><%= mascota.id %></th>
<td><%= mascota.a %></td>
</tr>
<% }) %>
<% } %>
</tbody>
</table>
index.ejs
<table class="table">
<thead>
<tr>
<th scope="col">name</th>
</tr>
</thead>
<tbody>
<% if(arrayMascotas.length > 0) { %>
<% arrayMascotas.forEach(mascota => { %>
<tr>
<td><%= mascota.state %></td>
</tr>
<% }) %>
<% } %>
</tbody>
</table>
app.js
app.use("/", require("./router/Rutasweb"));
app.use("/mascotas", require("./router/Mascotas"));
Mascotas.js
const express = require("express");
const router = express.Router();
const Mascota = require("../models/mascota")
router.get("/", async (req, res) => {
try {
const arrayMascotasDB = await Mascota.find()
console.log(arrayMascotasDB)
res.render("mascotas", {
arrayMascotas: arrayMascotasDB
})
} catch (error) {
console.log(error)
}
})
module.exports = router;

Cannot read property 'forEach' of undefined Nodejs/ejs/javascript

Iam facing the error Cannot read property 'forEach of undefined' for two days long and I just coudn't solve the problem. Your help would be very helpful. The code below
bruidstaart.js page where I want to show some data
<div class="table-wrapper">
<table class="table table-hovered">
<thead class="thead-dark">
<tr>
<th scope="col">Image</th>
<th scope="col">Bruidstaartnaam</th>
<th scope="col">Aantalpersonen</th>
</tr>
</thead>
<tbody>
<% bruidstaarten.forEach((bruidstaart, user) => { %>
<tr>
<td><img src="/assets/bruidstaartenmap/<%= bruidstaart.image %>" class="rounded-circle player-img" alt="" width="200" height="200"></td>
<td><%= bruidstaart.bruidstaartnaam %></td>
<td><%= bruidstaart.aantalpersonen %></td>
</tr>
<% }) %>
</tbody>
</table>
</div>
index.js
exports.bruidstaartenPage = function(req, res, next){
var sql1 = "SELECT * FROM `bruidstaarten` ORDER BY id ASC"; // query database to get all the players
db.query(sql1, function(err, result){
res.render('bruidstaartenPage', {bruidstaarten:result});
});
};
I figure it out by checking the query and the tabel in the database. id was wrong by creating the tabel

How to get a MySQL Value as a colour in EJS?

I have a table in my nodeJS project that has data with a status. I would like to show this status in red and green. To render the HTML page I use EJS.
I've already tried using an if/else statement, but there I always get the first value of the statement.
MySQL:
SELECT g_id, g_name, g_status FROM games
EJS:
<table class="table table-hover">
<thead>
<tr class="table-info">
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<% if (data) {
data.forEach(function(game){
var status = game.g_status;
if (status = '1') {
status = 'color-green';
} else {
status = 'color-red';
}
%>
<tbody id="myTable">
<tr>
<td><%= game.g_name %></td>
<td><%= status %></td>
</tr>
</tbody>
<% }) %>
<% } %>
</table>
What's the problem, and how do I get the SQL output to a specific colour?
use ternary condition like this way :
<table class="table table-hover">
<thead>
<tr class="table-info">
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<% if (data) {
data.forEach(function(game){ %>
<tbody id="myTable">
<tr>
<td><%= game.g_name %></td>
<td><%= game.g_status=='1'?'color-green':'color-red' %></td>
</tr>
</tbody>
<% }) %>
<% } %>
well.
there is many places to look for.
read on equals operator in JavasScript
status is not part of the list, just app variable
create function returning color for given status

How to display parsed data from ajax in express.js

I have this page made using node.js + express where I am displaying the following table :
I wish to reload only the table with new data using ajax when limit is changed using the dropdown (one with the label show result), but am having trouble doing so.
Here's the ejs code that displays my table :
<table class="assignment-table table table-striped table-bordered table-hover table-condensed table-responsive">
<thead>
<tr>
<th>S.No.</th>
<th>Name</th>
<th>Subject</th>
<th>Topic</th>
<th>Faculty</th>
<th>Posted</th>
<th>Last Date</th>
<th>Mode of Submission</th>
</tr>
</thead>
<tbody class="table_body">
<% for(var i =0;i< result.length;i++) { %>
<tr>
<td class="result_id">
<a target="_blank" href="/assignment/abc.pdf" class="download-link" id="">
<%= result[i]._id %>
</a>
</td>
<td class="result_name">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].nameAssignment %>
</a>
</td>
<td class="result_subject">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Subject %>
</a>
</td>
<td class="result_topic">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Topic %>
</a>
</td>
<td class="result_faculty">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Faculty %></a>
</td>
<td class="result_posted">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Posted %></a>
</td>
<td class="result_lastdate">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].LastDate %></a>
</td>
<td class="result_submission">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Submission %></a>
</td>
</tr>
<% } %>
</tbody>
</table>
In the filter_result() route mentioned above, I am fetching limit from the url and querying the database with new limits and rendering the page again.
Router.get('/filter_result',(req,res) => {
limit = parseInt( decodeURIComponent(req.query.limit) );
models.filterResults(limit, (count,result) => {
//if (err) throw err;
console.log(limit);
//res.send(result);
res.render('assignment-list',{limit:limit,result:result,count : count});
});
});
How can I redisplay the table in the ejs page?
Basically your .ejs format is rendered only once when you load or reload the page. So what you do is re-render (or, replace) the HTML from your AJAX call on top of already-rendered HTML.
It seems that you're using jQuery already so my example code uses jQuery too.
Re-rendering (or, again, replacing) HTML depends on what your /filter_result responds. If it's just bunch of <tr>s then it might be
JS
$('table.assignment-table').find('tbody').html(result);
If it's the entire <table> then you'd better wrap <table> with some wrapper like <div> and do the following.
HTML
<div id="table-wrapper">
<table>
...
</table>
</div>
JS
$('div#table-wrapper').html(result);
How you refer your wrapper and replace the content can vary.
Update 1
Assuming your API (/filter_result) returns an array of assignment objects like
{
"status": "success",
"data": [
{
"Subject": "Your subject",
"Topic": "Your topic",
...
},
...
]
}
you can create bunch of <tr/>s from data and replace the existing <tr/>s with them like (with jQuery of course. About creating DOM with jQuery, you can refer the docs.)
$.ajax({
method: 'GET',
url: 'URL_TO_FILTER_RESULT',
data: SOME_DATA,
success: function(res) {
var assignments = res.data;
var body = [];
assignments.forEach(function(assignment) {
var tr = $('<tr/>');
tr.append($('<td/>').html('' + assignment.Subject + '');
tr.append($('<td/>').html('' + assignment.Topic + '');
...
body.push(tr);
});
$('table.assignment-table').find('tbody').html(body);
}
})

How to call js for appropriate element

Can't how to deal with my problem: part of view are hidden, when page is loaded.
Here is this part:
<table>
<% #websites.each do |website| %>
<%if (current_user.id == website.user_id)%>
<tr>
<td> <%= link_to(image_tag("/images/caret-horizontal.png", id: "caret-horizontal"), '#') %> </td>
<td> <h4><%= website.name %></h4> </td>
</tr>
</table>
<table id="<%= website.id %>"> // or can be like this:
//I don't what variant is better
<table id="table-data" data-id="<%= website.id %>">>
<tr >
<td >
<%= website.url %>
</td>
</tr>
<tr>
<td >
<%= website.category %>
</td>
</tr>
<tr>
<td><%= website.language %></td>
</tr>
</table>
And I can get attributes in JavaScript like this(thanks to good people):
var yourWebsiteId = $("#table-data").attr("data-id");
How I can choose approriate element and show it? I should use getElementById or something like this, but I don't know exactly how to do it.
Please help me, if you can.
$("#table-data").show()
You can find information on this from here
$("#table-data") gets a reference to the part of the dom you are trying to access (# denotes id, . denotes class), once you have a reference you can then call any jquery operation you want on it

Categories

Resources