i am working on a project using express , EJS and SQLite, so i made search operation function that fetch data from the database, i want to display the data when i press the button, not before it, this is the function i made :
function findHomeforSell(req , res , next){
const sell = "sell";
db.all("SELECT * FROM home WHERE four like ?", [
sell
] ,function(err , rows){
if (err) { return next(err);}
var homes = rows.map(function(row) {
return {
id: row.id,
location: row.Location,
four: row.four,
space: row.space,
bathrooms: row.bathrooms,
bedrooms: row.bedrooms,
price: row.price,
url: '/' + row.id
}
});
res.locals.homes = homes;
next();
});
};
This is the route that requested when i press the button:
router.get('/buyHome', ensureLoggedIn ,fetchData,findHomeforSell , findHomeforRent, (req , res , next) => {
res.render('index', {user: req.user ,namor: res.locals.homes, rent: res.locals.rent});
next();
});
This is HTML form :
<form action="/buyHome" method="get">
<ul class="todo-list">
<% namor.forEach(function(namor) { %>
<li>
<div class="view" id="view">
<table>
<tr>
<th></th>
<th>Location</th>
<th>For</th>
<th>Space</th>
<th>Bathroom</th>
<th>Bedroom</th>
<th>Price</th>
</tr>
<tr>
<td rowspan="2"><img src="https://picsum.photos/200" id="circul" alt=""></td>
<td><%= namor.location %></td>
<td><%= namor.four %></td>
<td><%= namor.space %> SQRM</td>
<td><%= namor.bathrooms %></td>
<td><%= namor.bedrooms %> </td>
<td>$ <%= namor.price %> SDG</td>
</tr>
</table>
</div>
</li>
<% }); %>
</ul>
<input type="button" value="GO">
</form>
My problem is that the data appear before i call it or press the button
Related
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;
I have a code problem I need to do for a class. I have a database that has users, another table has the titles which the user has access to. I'm trying to make a page where they can edit a user and when they click the button the form fills automatically with the id, first name and last name fine.
Now I'm trying to show what access the user selected has access to at the moment. And what I thought would just be a simple if statement has turned into a headache, it seems I can't access the id variable inside the html code that I want to insert and when I try to put the if statement outside, it says errors with the http headers, like it is sending too many renders. How can I accomplish this?
So here the code works but it loads the tabs of all of the users but I would like to filter the results based on the id.
<tbody>
<% all_users_to_modify.forEach(function(row){ %>
<tr>
<td>
<button class="btn btn-primary m-b-0"
onClick="fillForm('<%= row.id %>','<%= row.f_name %>','<%= row.l_name %>');";
onclick="moneyCalc('<%= row.id %>')" >
<%= row.id %>
</button>
</td>
<td><%= row.f_name %></td>
<td><%= row.l_name %></td>
<td><%= row.email %></td>
<td><%= row.phone_number %></td>
</tr>
<% }); %>
</tbody>
<table class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th>Acceso</th>
</tr>
</thead>
<tbody id="lastResult">
</tbody>
</table>
function moneyCalc(id) {
'use strict';
var id = document.getElementById('id').value;
if (id) {
var html_to_insert = `
<% list_of_all_users_tabs.forEach(function(row1){ %>
<tr>
<td><%= row1.tab_name %> </td>
</tr>
<% }); %>
`;
lastResult.innerHTML += html_to_insert;
}
}
Now this is what I would like to do, in each row of the list_of_all_users_tabs it has a column that is the user_id and the other column is tab_name. So I have had two ideas but neither seem to work.
First idea was to put a while loop to compare the user_id in the db and the input id however I get: Error [ERR_HTTP_HEADERS_SENT]:
function moneyCalc(id) {
'use strict';
var id = document.getElementById('id').value;
if (id) {
while(list_of_all_users_tabs.user_id == id) {
var html_to_insert = `
<% list_of_all_users_tabs.forEach(function(row1){ %>
<tr>
<td><%= row1.tab_name %> </td>
</tr>
<% }); %>
`;
lastResult.innerHTML += html_to_insert;
}
}
}
Second idea had an if statement in the html code however it says id not defined:
function moneyCalc(id) {
'use strict';
var id = document.getElementById('id').value;
if (id) {
var html_to_insert = `
<% list_of_all_users_tabs.forEach(function(row1){ %>
<% if(row1.id == id) { %>
<tr>
<td><%= row1.tab_name %> </td>
</tr>
<% } %>
<% }); %>
`;
lastResult.innerHTML += html_to_insert;
}
}
Wrap your javascript code into <script> tag.
<script>
//Your code goes here
</script>
You need to set you header status to 200 in your route file.
res.json({
success: 'updated',
status: 200
})
And write you JS code inside <script> </script> tags only.
I am building an app (using EJS view engine and Node.js) which interacts with an MySQL database I have built locally. I can receive results from my queries successfully as a JSON string, but I cannot send the information to a view (to be displayed as HTML) as I am getting the error: unsafefoods is not defined.
My 'app.js' file declares:
var unsafefoods = require('./routes/unsafefoods');
app.use('/unsafefoods', unsafefoods);
My route 'unsafefoods.js' declares:
var express = require('express');
var router = express.Router();
/* GET all safe foods */
router.get('/', function (req, res, next) {
connection.query('SELECT * from appycavy.foods WHERE safe = 0', function (error, rows, fields) {
if (error) {
res.send(JSON.stringify({
"status": 500,
"error": error,
"response": null
}));
//If there is error, we send the error in the error section with 500 status
} else {
res.render(unsafefoods, {
title: 'Unsafe foods list',
data: rows
})
}
});
});
module.exports = router;
And my view 'unsafefoods.ejs' declares:
<!DOCTYPE html>
<html lang="en">
<head>
<% include ./partials/head %>
</head>
<body class="container">
<header>
<% include ./partials/header %>
</header>
<main>
<div class="jumbotron">
<h2>Safe foods</h2>
<p>The following is a list of all
<b>unsafe</b> foods
</p>
<!-- table to display unsafe foods -->
<table width='80%' border=0>
<tr style='text-align:left; background-color:#CCC'>
<th>ID</th>
<th>Name</th>
<th>Safe</th>
<th>Type</th>
<th>Favourite</th>
<th>Water</th>
<th>Energy</th>
<th>Vitamin C</th>
<th>Sugar</th>
<th>Lipid fat</th>
<th>Calcium</th>
<th>Phosphorus</th>
<th>CaP ratio</th>
</tr>
<!--
Using FOREACH LOOP for the users array
myArray.forEach(function(el, index) {
// el - current element, i - index
});
-->
<% if (data) { %>
<% data.forEach(function(unsafefoods){ %>
<tr>
<td><%= unsafefoods.id %></td>
<td><%= unsafefoods.name %></td>
<td><%= unsafefoods.safe %></td>
<td><%= unsafefoods.type %></td>
<td><%= unsafefoods.favourite %></td>
<td><%= unsafefoods.water %></td>
<td><%= unsafefoods.energy %></td>
<td><%= unsafefoods.vitaminC %></td>
<td><%= unsafefoods.sugars %></td>
<td><%= unsafefoods.lipidFat %></td>
<td><%= unsafefoods.calcium %></td>
<td><%= unsafefoods.phosphorus %></td>
<td><%= unsafefoods.capRatio %></td>
<td>
<div style="float:left">
<a href='/unsafefoods/edit/<%= unsafefoods.id %>'>Edit</a>
<form method="post" action="/unsafefoods/delete/<%= unsafefoods.id %>" style="float:right">
<input type="submit" name="delete" value='Delete' onClick="return confirm('Are you sure you want to delete?')" />
<input type="hidden" name="_method" value="DELETE" />
</form>
</div>
</td>
</tr>
<% }) %>
<% } %>
</table>
</div>
</main>
<footer>
<% include ./partials/footer %>
</footer>
</body>
</html>
Any pointers would be appreciated,
Thanks,
unsafefoods variable is undefined in your unsafefoods.js file.
Your code should be
res.render('unsafefoods', {
title: 'Unsafe foods list',
data: rows
})
you are missing '' around unsafefoods.
I am rendering the data created and edited in a js.erb to a datatable, the problem is that when making use of pagination, such data disappears. this my index:
<table id="superior" class="display"><!--el id activos es de datatables referenciado en activos.coffe y display class es una clase de datatables-->
<thead>
<tr><!--active es para sombrear la fila-->
<th>Id</th>
<th>DescripciĆ³n</th>
<th>Modelo</th>
<th>FechaAlta</th>
<th>Serie</th>
<th>CB</th>
<th>Imagen</th>
<th>Status</th>
<th>Acciones</th>
<th></th>
</tr>
</thead>
<tbody id="container_activos">
<%= render #activos %><!--carga todos los activos-->
</tbody>
</table>
my partial _activo.html.erb
<tr id="activo_<%= activo.id %>">
<td><%= activo.IdActivos %>
</td>
<td><%= activo.Descripcion %></td>
<td><%= activo.Modelo%> </td>
<td><%= activo.Fecha%>></td>
<td><%= activo.Serie %></td>
<td><%= activo.CB %></td>
<td id="producto-imagen" >
<%= image_tag activo.cover.url(:minithumb) %>
</td>
<td><%= activo.Status %>
</td>
<td>
<button type="button" class="btn btn-warning btn-xs" data-toggle="modal" data-target="#myupdateactivo_<%= activo.id %>">
Editar
</button>
</td>
<td>
</td>
</tr>
my create.js.erb:
$("#mynewactivo").modal('hide');
$("#container_activos").prepend('<%= j render #activo %>'); //Prepend before append
$("#activo_<%= #activo.id %>").hide().fadeIn(1000);
$("#notice").html("<%= escape_javascript(render :partial => 'partials/flash' , :locals => { :flash => flash }).html_safe %>");
setTimeout(function(){
$('#notice').fadeIn("slow", function() {
$(this).create();
})
}, 1500);
my update.js.erb:
$("#myupdateactivo_<%= #activo.id %>").modal('hide');
$("#mynewactivoenvase").modal('show');
$("#activo_<%= #activo.id %>").fadeOut(500, function(){
$(this).remove();
$(".child").remove();
$("#container_activos").prepend('<%= j render #activo %>');
});
$("#notice").html("<%= escape_javascript(render :partial => 'partials/flash' , :locals => { :flash => flash }).html_safe %>");
setTimeout(function(){
$('#notice').fadeIn("slow", function() {
$(this).create();
})
}, 1500);
I am building a timesheet form that consists of a calendar which enables a user to select a specified date, and search for a project. I have this functionality working. What I basically have is this:
Once the user searches for their project and press the plus button, that specified project. Which in this instance is Asda the user would then click the plus icon which would create a new row and put it into the table 'task for project. How can you do this in Javascript/JQuery.
Sorry for asking what may be seen as such a basic question, but am still learning Javascript/JQuery.
I currently have the plus icon linked to project_project_tasks_path( project.id ). This is just temporary.
This is what I have so far:
<div class="left">
<table border="2" width="" id='projects' class='datatable'>
<thead>
<tr>
<th>Number  </th>
<th>Name</th>
<th></th>
</tr>
</thead>
<tbody>
<% #projects.each do |project| %>
<tr>
<td><%= project.project_number %></td>
<td><%= project.project_name %></td>
<td><%= link_to image_tag("icons/add.png"), project_project_tasks_path( project.id ), :remote => true %></td>
<!-- link_to image_tag("icons/add.png"), tasklist_path(project.id), :as => "tasklist" -->
</tr>
<%- end -%>
</tbody>
</table>
</div>
<div class="right">
<b>Recently Viewed</b>
<table>
<tr>
<th>Project No.</th>
<th>Project names</th>
<th>Project Leader</th>
<th></th>
</tr>
<tr>
<td>123</td>
<td>Test</td>
<td>1</td>
<td><%= link_to image_tag("icons/add.png") %></td>
</tr>
</table>
</div>
</fieldset>
<fieldset>
<b><center>Hours for Week commencing: <span id="startDate"><%= Date.today.beginning_of_week.strftime('%d/%m/%Y') %></span></center></b>
</fieldset>
<!-- Task list table -->
<div style="float: right; width: 300px; padding-left: 20px;">
<fieldset>
<b>Tasks for project</b>
<ul id="task_list">
</ul>
</fieldset>
</div>
<!-- Hours list table -->
<fieldset>
<table>
<tr>
<td>Leave</td>
<td><input class="dayinput" type="text" name="Leave"></td>
</t>
<tr>
<td>TOIL</td>
<td><input class="dayinput" type="text" name="TOIL"></td>
</tr>
<tr>
<td>Sick</td>
<td><input class="dayinput" type="text" name="Sick"></td>
</tr>
<tr>
<td>Total</td>
<td><input id="total" class="total_low" type="text" value="0" disabled="">
</tr>
</table>
</fieldset>
Edited:
I have created a task_list.js.erb which is as followed:
$('#task_list').html('');
<% #project.project_tasks.each do |task| %>
$('#task_list').append('<ul><%= task.task_name %>');
<% end %>
Project Controller
def index
# check if we've got a project id parameter
if( params[:project_id].nil? )
#project = nil
else
#project = Project.find(params[:project_id])
end
if #project.nil?
#project_tasks = ProjectTask.all
else
#project_tasks = Project.find(params[:project_id]).project_tasks
end
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #project_tasks }
format.js # index.js.erb
end
end
From the changes made, it outputs:
JQuery Ui autocomplete code:
$(function() {
function log(message) {
$( "<div/>" ).text( message ).prependTo("#log");
}
$("#tags").autocomplete({
source : function(request, response) {
$.ajax({
url : "/projectlist",
dataType : "json",
data : {
style : "full",
maxRows : 12,
term : request.term
},
success : function(data) {
var results = [];
$.each(data, function(i, item) {
var itemToAdd = {
value : item,
label : item
};
results.push(itemToAdd);
});
return response(results);
}
});
}
});
});
Adding to the DOM with jQuery is very simple with the append or prepend method.
$('element_to_add_to').append('the html to append');
$('element_to_add_to').prepend('the html to append');
Check out the empty method in the jQuery docs as well.
Also, you have some bad markup. The task_list <ul> has no <li>'s and the table in there has an extra </tr>.
Edit: From your updated post, it seems like you want to not only insert a row in a table, but also save the data to your database at the same time. In that case, you'll want to make an ajax call to a controller method which will save the data in your DB. Then add the updated row to the table if the call is successful.
$.ajax({
type: "POST",
url: "path to your route",
data: "the data to send to your controller",
success: function(data){
// here is where you process the return value from your controller method
// the data variable will hold the return value if the call is successful
// you can make your controller return the html to be inserted in your table
// and insert it from here or just return a status message and build and add
// the html manually here.
}
});