Displaying MySQL query results as HTML with EJS - javascript

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.

Related

ExpressJS: i want to fetch data from database

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

Using ejs input for js if statement

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.

How can use onclick on different table td in jquery?

I have one looping Dates and table content.
I want to display table content based on Dates. How's it possible please help me.
index.html.erb
<% #batches.each do |batch| %>
<tr>
**<td class = "pie" id ="demo"> <i class="fa fa-plus-circle"></i>
<%= batch.date.strftime("%Y-%m-%d") if !batch.date.nil? %></td>**
<td><%= batch.purchase_center.name.to_s if !batch.purchase_center.nil? %></td>
<td><%= batch.plant.name.to_s if !batch.plant.nil?%></td>
<td><%= batch.species.name.to_s if !batch.species.nil? %></td>
<td><%= batch.batch_number %></td>
<td><%= batch.total_quantity %></td>
<td><%= batch.calculated_yeild %></td>
<td><%= link_to '<i class="fa fa-users"></i>'.html_safe, "#", :class => "addsupplier", :id => "#{batch.serial_id}" %></td><td><%= link_to '<i class="fa fa-trash-o"></i>'.html_safe, batch, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<tr class="<%= batch.serial_id %>" style="display:none">
<%= render :partial => "batch_counts/form", locals: {id: "#{batch.serial_id}"} %>
</tr>
**<td id ="two" style="display:">
Microsoft Corporation
Microsoft Corporation
</td>**
<% end %>
<script type="text/javascript">
$('#demo').click(function(){
$('#two').toggle();
});
</script>
I highlighted with star marks i.e. id = demo and id =two.
i have different dates and different message. So i want to display it on which date is having which message.
Based on dates display message.
Give a common class to each of them. Say, date-alert:
<td class="pie date-alert" id="demo"> <i class="fa fa-plus-circle"></i>
<%= batch.date.strftime("%Y-%m-%d") if !batch.date.nil? %></td>
<td id="two" style="display:" class="date-alert">
Microsoft Corporation
Microsoft Corporation
</td>
And then upon clicking it, you can execute like this:
$(".date-alert").click(function () {
// the current td is this
});

Iterate over an array by index when click on submit button Ruby on Rails

I have an array of Pet instances and each of them have a name, type, sex and size, etc... I'd like to iterate through this collection of Pet instances and display the each one by one.
This is what I have so far:
<% #pets.each do |pet| %>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Sex</th>
<th>Age</th>
<th>breed</th>
<th>Size</th>
<th>Picture</th>
<th>Description</th>
<th>Shelter_id</th>
<th>Shelter</th>
<th>Phone</th>
<th>Email</th>
<th>City</th>
<th>Zip</th>
<th>Like</th>
</tr>
</thead>
<tbody>
<tr>
<td><%= pet.name %></td>
<td><%= pet.species %></td>
<td><%= pet.sex %></td>
<td><%= pet.age %></td>
<td><% pet.breeds.each do |breed| %>
<li><%= breed.name %></li>
<%end%>
</td>
<td><%= pet.size %></td>
<td><%= image_tag pet.picture %></td>
<td><%= pet.description %></td>
<td><%= pet.shelter_id %></td>
<% shelter = Shelter.find(pet.shelter_id)%>
<td><%= shelter.name %></td>
<td><%= shelter.phone %></td>
<td><%= shelter.email %></td>
<td><%= shelter.city %></td>
<td><%= shelter.zip %></td>
<td><%= form_for pet, :url => { :controller => "favorite_pets", :action => "create" }, :html => {:method => :post} do |f| %>
<%= f.text_field :id %>
<%= f.submit %>
<% end %>
</td>
</tr>
</tbody>
</table>
<%end%>
So now, I need two thinks.
1st
When a user clicks the submit button (<%= f.submit %>) to send a POST request i do not want the page to reload nor to redirected me to another page. I looked around and it seems like :remote => true included in the form_for would do the trick but i'd need more help with that.
2nd
I'd like to control the iterating through #pets so that only the first one is displayed pet[0] and every time I click on the <%= f.submit %> button not only does it not reload the page but it displays the next index in the array pet[1]
I think I need to set up a sort of counter which would increment the index of the pet array every time a user click on the <%= f.submit %> button.
Any guiding thoughts?
If I were to do this I would use some javascript. So your submit button turns into more of an "Add Button" it doesn't actually submit anything. It would just add that object (in your case the pet, along with its info) to a javascript array as well as display the new object (again the pet along with the info) on the window. Then create another button to actually submit all the pets. (The javascript array)

Rails jQuery sortable unable to save

I'm trying to make my table sortable (drag and drop) using jQuery, the problem I'm having is saving the new sorted table and then publishing it to other users or when the browser is refreshed.
I'm using:
gem 'acts_as_list'
Rails 3.2.17
ruby 1.9.3p484
Is there a better way of doing this?
my sort and show method on my controller
def sort
#episodes = current_user.episodes_for(#show).each do |episode|
episode.position = params['episode'].index(episode.id.to_s) + 1
episode.save
end
render :nothing =>true
end
def show
#episodes = current_user.episodes_for(#show)
#episodes.order('episode.position ASC')
#episode = #episodes.where(id: params[:id]).first
end
My Javascript
<script>
$(window).load(function() {
$("#sortthis").sortable({
axis: 'y',
placeholder: 'ui-state-highlight',
cursor: 'move',
dropOnempty: false,
scroll: true,
opacity: 0.4,
update: function(event, ui){
var itm_arr = $("#sortthis").sortable('toArray');
var pobj = {episodes: itm_arr};
$.post("/episodes/sort", pobj);
}
});
});
</script>
The table I wanna sort in views:
<tbody id='eps'>
<tr>
<th>Title</th>
<th>#</th>
<th>Season</th>
<th>Download?</th>
<th>Shared?</th>
<th>Length</th>
<th>Status</th>
<th></th>
</tr>
<% for episode in #episodes %>
<tr>
<td id="eps_<%= episode.id %>", width="20%"><%=h episode.title %></td>
<td id="eps_<%= episode.id %>"><%=h episode.number %></td>
<td id="eps_<%= episode.id %>"><%=h episode.season %></td>
<td id="eps_<%= episode.id %>"><%=h episode.is_downloadable %></td>
<td id="eps_<%= episode.id %>"><%=h episode.shared_with_dev %></td>
<td id="eps_<%= episode.id %>"><%=h episode.length %></td>
<td>
<% if episode.video %>
<%= link_to 'Replace Video', new_show_episode_video_path(episode.show, episode) %>
<% else %>
<%= link_to 'Upload Video', new_show_episode_video_path(episode.show, episode) %>
<% end %>
</td>
<td>
<%= link_to "View", [episode.show, episode] %>
<%= link_to "Edit", edit_show_episode_path(episode.show, episode) if permitted_to? :update, episode %>
<%= link_to "Delete", show_episode_path(episode.show, episode), :confirm => 'Are you sure?', :method => :delete if permitted_to? :delete, episode %>
</td>
</tr>
<% end %>
any help will be greatly appreciated!
I figured it out, made the following changes:
Views:
<tr id="<%= episode.id %>">
and new controller
def sort
Episode.all.each do |e|
if position = params[:episodes].index(e.id.to_s)
e.update_attribute(:position, position + 1) unless e.position == position + 1
end
end
render :nothing => true, :status => 200
end
finally added this to my model:
acts_as_list
default_scope order('position')
let me know if anyone's having similar issues.

Categories

Resources