How to create table handlebars with nodejs - html

Guys I have the following json server.js:
const express = require("express")
const app = express()
const http = require('http').Server(app);
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./conta.sql')
const handlebars = require("express-handlebars");
const bodyParser = require("body-parser")
app.use(express.static(__dirname + "/css/"));
app.use(bodyParser.urlencoded({extended:true}));
app.engine('handlebars', handlebars({defaultLayout:false}));
app.set('view engine', 'handlebars');
function getallusers(req,res) {
try{
data = [
{
id: 1,
nome: 'Ronnica Hardison',
data: '2021-09-31 04-54-00',
email: 'test#gmail.com',
nome_bonus: 'John Watson',
cod_bonus: 'piwi20k9'
},
{
id: 2,
nome: 'Kellie Jean Abernethy',
data: '2021-09-31 23-50-00',
email: 'gobirob190#mnqlm.com',
nome_bonus: 'Ámelia Barton',
cod_bonus: 'piwiki20k9'
}
]
res.render(__dirname + "/index.handlebars")
}
catch(err){
console.log("\x1b[31m Problema ao carregar as informações do banco de dados!",err);
}
}
app.get('/', function(req,res){
getallusers(req,res)
});
http.listen(8083,() => {
console.log("Servidor escutando na porta 8083");
});
index.handlebars:
<center>
<div class="table">
<table cellspacing="0">
<thead>
<tr class="indices">
<th>Nome</th>
<th>Email</th>
<th>Data de Criação</th>
<th>Convidada de</th>
<th>Codico usado</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
{{data here}}
</tr>
</tbody>
</table>
</div>
</center>
So guys... what I needed to do was render the json data in the table, how can I do this? What I need is to create <th> tags according to the json information, but this has to be dynamic. The json information can be different, ie it's dynamic, so how can I render this?

Try this:
in your server.js pass data to index.handlebars file:
res.render(__dirname + "/index.handlebars",{data})
and in index.handlebars use this
<center>
<div class="table">
<table cellspacing="0">
<thead>
<tr class="indices">
<th>Nome</th>
<th>Email</th>
<th>Data de Criação</th>
<th>Convidada de</th>
<th>Codico usado</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{{#each data}}
<tr>
<th scope="row">{{this.id}}</th>
<td>{{this.nome}}</td>
<td>{{this.email}}</td>
<td>{{this.nome_bonus}}</td>
<td>{{this.cod_bonus}}</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
</center>

Related

How to display image from MySQL in ReactJS using Express

I have uploaded an image in the images folder of my Node server and the path is stored in the MYSQL database. I want to display the image in my ReactJS application. I am getting the error:
http://127.0.0.1:8080/images/abc.jpg 404 (Not Found)
const baseURL = "http://localhost:8080/data";
export default function Displaydata() {
const [userdata, setuserdata] = React.useState([]);
React.useEffect(() => {
axios.get(baseURL)
.then((response) => {
setuserdata(response.data);
console.log(response.data);
});
}, []);
if (!userdata) return null;
return (
<>
<h2>Data</h2>
<table border="1">
<thead>
<tr>
<th>S.No</th>
<th>userid</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{userdata.map(({ userid, name,image },index) => {
let sno=0;
return (
<tr key={userid}>
<td>{index + 1}</td>
<td>{userid}</td>
<td>{name}</td>
<td><img src={image} alt={image}/></td>
</tr>
);
})}
</tbody>
</table>
</>
);
}
What can I try to fix this?

Displaying multiple jsons in VUE

So this is my code
<script>
export default {
name: "app",
data() {
return {
items: []
};
},
created: function() {
this.makeAjaxCall("books.json", "get").then(res => {
this.items = res
return res
}),
this.makeAjaxCall("authors.json", "get").then(resA => {
this.items = resA
return resA
})
},
methods: {
makeAjaxCall:function(url, methodType){
var promiseObj = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
//alert("xhr done ok");
var response = xhr.responseText;
var respJson = JSON.parse(response);
resolve(respJson);
} else {
reject(xhr.status);
//alert("xhr failed");
}
} else {
//alert("xhr processing");
}
}
//alert("request sent succesfully");
});
return promiseObj;
}
}
};
</script>
<template>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
<th>Availability</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img id="imageBook" :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
</div>
</template>
I have the function makeAjaxCall that brings me the books.json, but I want to use it for multiple jsons.
I tried to call it under created, with a different json, authors.json, but it doesn't work.
I guess the syntax is wrong.
I know the function could have been created better, but I would like to keep its initial form or maybe add a parameter to be the json file.(Tried that, but didn't work for me)
Any ideas, pretty please?
To bind the data you have to declare first items: {books:[],authors:[]}
Also you are overwriting this.items use this.items.books and this.items.authors to assign.
Below is the example which works without ajax
new Vue ({
el: "#app",
data() {
return {
items: {books:[],authors:[]}
};
},
created: function() {
this.items.books = this.makeAjaxCall("books", "get");
this.items.authors = this.makeAjaxCall("authors", "get");
},
methods: {
makeAjaxCall:function(url, methodType){
if(url == 'books'){
promiseObj= [{name:'name11',author:'author11',genre:'genre11'},{name:'name12',author:'author12',genre:'genre12'}]
}else{
promiseObj= [{name:'name22',author:'author22',genre:'genre22'}]
}
return promiseObj;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.js"></script>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
<table class="authorsTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.authors" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
</div>
So I found the answer, after millions of tries and it's pretty simple.
<script>
import './styling.scss'
export default {
name: "app",
data() {
return {
items: {books:[], authors:[]}
};
},
created: function() {
this.makeAjaxCall("books.json", "get").then(res => {
this.items.books = res.books;
return res;
}),
this.makeAjaxCall("authors.json", "get").then(res => {
this.items.authors = res.authors;
return res;
})
},
methods: {
makeAjaxCall:function(url, methodType){
var promiseObj = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
//alert("xhr done ok");
var response = xhr.responseText;
var respJson = JSON.parse(response);
resolve(respJson);
} else {
reject(xhr.status);
//alert("xhr failed");
}
} else {
//alert("xhr processing");
}
}
//alert("request sent succesfully");
});
return promiseObj;
}
}
};
</script>
<template>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
<th>Availability</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img id="imageBook" :src="item.imageUrl"></td>
<td>
<button class="btn add"> Add</button>
<button class="btn edit"> Edit</button>
<button class="btn delete"> Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>

select all checkboxes with angular JS

I am trying to select all checkboxes with one single checkbox. But how to do that?
This is my HTML:
<input type="checkbox" ng-model="selectAll" ng-click="checkAll()" />
<!-- userlist -->
<!--<div id="scrollArea" ng-controller="ScrollController">-->
<table class="table">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Select</th>
</tr>
<tr ng-repeat="user in users | filter:search">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td><input type="checkbox" ng-click="usersetting(user)" ng-model="user.select"></td>
<td><tt>{{user.select}}</tt><br/></td>
</tr>
</table>
I create an extra checkbox to selecet and unselect all checkboxes.
JS:
.controller('UsersCtrl', function($scope, $http){
$http.get('users.json').then(function(usersResponse) {
$scope.users = usersResponse.data;
});
$scope.checkAll = function () {
angular.forEach($scope.users, function (user) {
user.select = true;
});
};
});
I tried this too, but none of them works for me :(
$scope.checkAll = function () {
angular.forEach($scope.users, function (user) {
user.select = $scope.selectAll;
});
};
You are missed the container divs with ng-controller and ng-app and angular.module.
user.select = $scope.selectAll is the correct variant.
https://jsfiddle.net/0vb4gapj/1/
Try setting the checked boxes against each user to be checked when the top checkbox is checked:
<input type="checkbox" ng-model="selectAll"/>
<table class="table">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Select</th>
</tr>
<tr ng-repeat="user in users | filter:search">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td><input type="checkbox" ng-click="usersetting(user)" ng-model="user.select" ng-checked="selectAll"></td>
<td><tt>{{user.select}}</tt><br/></td>
</tr>
</table>
Here is a JSFiddle you can use ng-checked with a variable on it like user.checked (or use the user.select as you want)
<div ng-app="app" ng-controller="dummy">
<table>
<tr ng-repeat="user in users">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>
<input type="checkbox" ng-click="usersetting(user)" ng-checked="user.checked" ng-model="user.select">
</td>
<td><tt>{{user.select}}</tt>
<br/>
</td>
</tr>
</table>
<button ng-click="checkAll()">Check all</button>
</div>
JS:
var app = angular.module("app", []);
app.controller('dummy', function($scope) {
$scope.users = [{
id: 1,
name: "Hello",
select: 1
}, {
id: 2,
name: "World",
select: 1
}, ];
$scope.checkAll = function() {
angular.forEach($scope.users, function(user) {
user.checked = 1;
});
}
});
Simple use the following code
HTML
<input type="checkbox" ng-model="checkboxes.checked" data-ng-click="checkAll()" class="select-all" value="" />
JS
$scope.checkAll = function() {
angular.forEach($scope.users, function(item) {
$scope.checkboxes.items[item._id] = $scope.checkboxes.checked;
$scope.selection.push(item._id);
});
}

using ng-repeat to display data in json file

I am new to angularjs. I want to display the data in the following json file using ng-repeat.
http://www.cricbuzz.com/api/match/current
But I'm confused as there is a number in the data as key to each object. Can someone help me?
THis is a basic way to do it
Partial
<div ng-controller="Ctrl" >
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in rows">
<td>#{{ row.id}}</td>
<td>{{ row.series.name | uppercase }}</td>
</tr>
</tbody>
</table>
</div>
Controller
angular.module('app').controller('Ctrl', ['$scope', 'Resource', function ($scope, Resource) {
var pageChanged = function () {
$scope.myPromise = Resource.get({}, function (response) {
$scope.rows = response;
});
};
pageChanged();
}])
.factory('Resource', ['$resource', function($resource) {
return $resource('http://www.cricbuzz.com/api/match/current', {
}, {
'get': {
method: 'GET',
headers: {"Content-Type": "application/json"}
}
});
}]);

Add data from GET-request to table in HTML using ng-repeat

I'm having trouble with adding rows to a table in my HTML, which comes from an array containing objects.
When I run my code I do a $get request like so:
var app = angular.module('TM', []);
app.controller('tableController', function($http){
this.protocolList = [];
// Initialise array
$http.get('../protocols').success(function(data) {
console.log('Success ' + data);
this.protocolList = data;
angular.forEach(this.protocolList, function(value, key) {
console.log(key + ': ' + value.id + ' - ' + value.name);
});
})
.error(function(){
console.log('Error ' + data)
});
});
When I open up my web browser, I see the following:
My problems occure when I try to add this to a table in my HTML-file:
<table class="table table-striped">
<thead>
<tr>
<th ng-repeat="c in tctrl.currentDataObject.tableColumns"> {{ c }} </th>
</tr>
</thead>
<!-- This does not ouput anything...-->
<tbody>
<tr ng-repeat="(key, value) in tctrl.protocolList">
<td> {{ value }} </td>
</tr>
</tbody>
</table>
Any help will be much appreciated.
U don't need to inject $scope like this to get access to the DOM??
app.controller('tableController', function($scope,$http){
Im not sure if it is implicit.
Try this simple example:
app.controller('tableController', ['$scope', '$http', function($scope, $http){
$scope.protocolList = [];
// Initialise array
$http.get('../protocols').success(function(data) {
console.log('Success ' + data);
$scope.protocolList = data;
})
.error(function(){
console.log('Error ' + data)
});
}]);
HTML:
<table class="table table-striped">
<thead>
<tr>
<th ng-repeat="c in tctrl.currentDataObject.tableColumns"> {{ c }} </th>
</tr>
</thead>
<!-- This does not ouput anything...-->
<tbody>
<tr ng-repeat="item in protocolList">
<td> {{ item.id }} </td>
<td> {{ item.name }} </td>
</tr>
</tbody>