I have this function on my backend:
app.get('/dashboard', async(req, res) => {
const customers = await stripe.customers.list();
customers.data.forEach(customer => {
console.log(customer.metadata);
});
res.render('dashboard.ejs', {customer: customers})
})
and on my front end:
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>NAME</th>
<th>EMAIL</th>
<th>ACTIONS</th>
</tr>
</thead>
<tbody>
<% if(customer.length){
for(var i = 0;i < customer.length;i++) { %>
<tr>
<td><%=customer[i].NAME%></td>
<td><%=customer[i].EMAIL%></td>
<% }
}else{ %>
<% } %>
</tbody>
</table>
however, i am trying to pass the METADATA to the front end. and within the metadata object, i have name and email. So on the front end, i tried:
<%=customer[i].METADATA.NAME%>
but it returned nothing. and same on the backend. how can i fix this?
In the comments above, by fetch I mean the term fetch you need to some how connect to your backend to accept the data on front end. You can use ajax, axios, fetch API etc.... Below I used ajax to show how to get data from back end. Feel free to comment if you have any questions?
var data_from_backend;
$.ajax({
type: 'GET',
data: 'data_to_send_to_backend',
url: 'server_URL',
success: function(getMetadata) {
$.each(JSON.parse(getMetadata), function(myMetadata) {
data_from_backend = myMetadata.the_name_of_data_set_on_backend
})
},
error: function(data) {
console.log('Something went wrong.');
}
});
console.log(data_from_backend)
Related
I have a search box which I wish to use to populate my table so i want to access the data sent to the view template in the script tag
ERROR IN SCRIPT
1 Uncaught SyntaxError: "[object Object]" is not valid JSON
at JSON.parse (<anonymous>)
at 1:164:25
<div class="FieldElement2" style="margin-top: 3%;">
<div class="input-field ">
<input id="search_masterTable" type="text" class="validate">
</div>
<table class="highlight centered responsive-table" style="width: min-content;" >
<thead>
<tr>
<th></th>
<th>Ledg.No.</th>
<th>File No.</th>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
<tbody id="searchResultsBody">
{{#each accounts_array}}
<tr>
<td><button class="viewButton">View Chart</button></td>
<td class="Ledg_No" scope="row">{{ledger_num}}</td>
<td class="File_Num" scope="row">{{file_num}}</td>
<td class="Name">{{client_name}}</td>
<td class="gPhoneNumber3">{{phone_number6}}</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
<script>
document.getElementById('search_masterTable').addEventListener('input',()=>{
const search_value = document.getElementById('search_masterTable').value.toUpperCase().split(' ')
// NOT WOKING
const data = JSON.parse("{{accounts_array}}")
const result_array = data.filter(function(r){
return search_value.every(function(word){
console.log(word)
return column_name_array.some(function(colIndex){
console.log(r[colIndex])
if(r[colIndex] == null){
return false
}else{
return r[colIndex].toString().toUpperCase().indexOf(word) !== -1
}
});
});
})
function to_populate_masterTable(){
}
</script>
insted of sending the search value back to the server i want to perfom the search opearation in the frontend and send display the result for every search input
BACK END
router.get('/masterTable/:id', ensureAuth, async (req, res) => {
const title = 'Master Table'
var account = parseInt(req.params.id)
db.query(`SELECT * FROM mt_`+account+``, async (err,accounts_array) => {
res.render('masterTable', {
accounts_array,
title
})
})
})
THIS IS WHAT THE account_array LOOKS LIKE
[
RowDataPacket { // <= this is the error
id: 1,
ledger_num: 'VM364',
file_num: 'VM364',
client_name: 'MUTHU KUMAR',
phone_number1: '9791716460',
status: 'UNSETTLED'
},
RowDataPacket {
id: 1,
.,
.,
.,
},
RowDataPacket {},
RowDataPacket {}
]
error that i got
Uncaught SyntaxError: Unexpected token '{' (at 1:169:21)
This might work by first stringifying the variable and using the tag syntax to pass the stringified JSON to the template:
const data = JSON.parse(<%= JSON.stringify(accounts_array) %>);
I am currently using a CRUD made with NodeJS + MYSQL. I recently integrated my tables with Jquery Datatables Plugins, but I would like to add a custom column in which to return any information as a prefix in the ID.
example, a column of the type
ID | NAME | CPF | ACTIONS
01 | JAIR | 123 | IAMID01
I was reading something about object mapping but the maximum I got was that.
db.js
exports.execSQLQuery = (sqlQry, res) => {
var connection = mysql.createConnection({
host : 'localhost',
port : 3306,
user : 'root',
password : '',
database : 'nodejs'
});
connection.query(sqlQry, function(error, results, fields){
if(error)
res.json(error);
else
//*PASSAR RESULTADO PARA UMA VARIAVEL
//var rows = JSON.parse(JSON.stringify(results[0]));
res.json(results);
connection.end();
console.log('executou!');
});
};
tabela.html
<script type="text/javascript">
$(document).ready(function(){
$.get('/dados',function(dados){
// data is a JS object parsed from a JSON response
var ids = dados.map(elemento => elemento.ID);
console.log(ids)
$('#example').DataTable({
"ajax":{
"url":"/dados",
"dataSrc": ""
},
"columns":[
{ "data":"ID"},
{ "data":"Nome"},
{ "data":"CPF"},
{
data: null,
className: "center",
defaultContent: ids
}
]
});
});
});
</script>
</head>
<body>
<table id="example" class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Office2</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Office2</th>
</tr>
</tfoot>d
</table>
</body>
clientesController.js
module.exports = {
getDados : function(req,res){
execSQLQuery('SELECT * FROM Clientes',res);
},
You should alter your table and add the column as an self-incremental field.
ID Integer PRIMARY KEY AUTOINCREMENT
After that every new record in your table will autogenerate a new id.
New to coding, so I apologize for any rookie mistakes.
I am attempting to query a MySQL database and return the results to a table. I will be submitting the SQL query via a form on the site, so the number and names of the columns will be dynamic. I have seen how this is done in PHP but I would like to do this via node.js and ejs. I have been able to figure out how to have all the rows of the query results show in a table. Here are examples of the code.
query.ejs
<table id="table" >
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<% print.forEach(function (RowDataPacket) { %>
<tr>
<td><%= RowDataPacket.id %></td>
<td><%= RowDataPacket.name %></td>
</tr>
<% }) %>
</tbody>
</table>
app.js
app.post("/query", function(req, res) {
console.log(req.body.sql);
var sqlStatement = req.body.sql;
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
if (err) {
throw err;
} else {
obj = {
print: result
};
res.render('query', obj);
}
});
I'm trying to push an ajax response array into MVC table. This is how my script looks like:
<script type="text/javascript">
$(document).ready(function () {
$('#form1').submit(function (event) {
event.preventDefault();
event.returnValue = false;
var selectValue = $('#selectValue').val();
$.ajax({
url: "/api/Admin/GetDepotDetails/",
type: "POST",
data: { "selectValue": selectValue },
dataType: "json",
success: function (data) {
$("#Grid").html($(data).children());
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
alert(textStatus, errorThrown, jqXHR);
}
});
});
});
</script>
This is how my partial view looks like:
#model IEnumerable<SampleApp.DepotDetail>
<table class="table table-condensed" id="Grid">
<tr>
<th>
#Html.DisplayNameFor(model => model.DepotID)
</th>
<th>
#Html.DisplayNameFor(model => model.ColumnName)
</th>
<th>
#Html.DisplayNameFor(model => model.Country)
</th>
<th>
#Html.DisplayNameFor(model => model.CountryCode)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr class="warning">
<td>
#Html.DisplayFor(modelItem => item.DepotID)
</td>
<td>
#Html.DisplayFor(modelItem => item.ColumnName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Country)
</td>
<td>
#Html.DisplayFor(modelItem => item.CountryCode)
</td>
</tr>
}
</table>
This is how the WebApi method looks like:
[HttpPost]
public IEnumerable<DepotDetail> GetDepotDetails(Selected selectValue)
{
var model = depotsDetails.Where(x => x.ColumnName == selectValue.SelectValue) as IEnumerable<DepotDetail>;
var viewModel = new SearchViewModel{ DepotDetailsList = model, ActionLists = new ActionList()} ;
return model;
}
This is how the View looks like:
#model IEnumerable<SiemensSampleApp.DepotDetail>
<div class="row">
<div class="col-md-4">
<form id="form1">
#*#Html.DropDownListFor(model => model.DepotListSelectValue, Model.DepotLists, new { #class = "form-control" })*#
#Html.DropDownList("selectValue", new List<SelectListItem>
{
new SelectListItem() {Text = "Depot ID", Value="Depot ID"},
new SelectListItem() {Text = "Depot Name", Value="Depot Name"},
new SelectListItem() {Text = "Address", Value="Address"}
}, new { #class = "selectValue", #id = "selectValue" })
#*//, new { #class = "chzn-select", #id = "chzn-select" }*#
<input type="submit" value="submit" />
</form>
<br /><br /><br />
<table id="records_table" style="width:100%;"></table>
<div id="tableHere">
#{
if (Model == null)
{
Html.RenderPartial("_SearchResult", new List<DepotDetail>() { });
}
}
</div>
</div>
</div>
Question: Through WebApi i'm trying to get a List of details and bind it to a MVC table. What is the best way to do this?
I have used
$("#Grid").html($(data).children());
To fill the Grid. But the table doesn't have any data. can someone please give me an idea how to fill the grid using above Partial view.
Thank you in advance!
Your web api endpoint return data ( in json format), not the HTML markup from your partial view. You have 2 options.
1) Create an mvc action method which gets the data and pass it to your partial view and return the partial view response and use that to update your UI
[HttpPost]
public IEnumerable<DepotDetail> GetDepotDetails(Selected selectValue)
{
var model = depotsDetails.Where(x => x.ColumnName == selectValue.SelectValue)
as IEnumerable<DepotDetail>;
return PartialView(model);
}
Now make sure you have a partial view called GetDepotDetails.cshtml in ~/Views/Shared or ~/View/YourControllerName/. This view should be strongly typed to a collecction of DepotDetail.
#model IEnumerable<DepotDetail>
<p>Here loop through each item in Model and render the table</p>
<p> Same as your partial view in the question </p>
And in your success event,
success: function (data) {
$("#Grid").html(data);
},
2) Use your current web api endpoint and read the data in your ajax method's success event and dynamically build the html markup for the table rows and set that as the content of your Grid table.
success: function (data) {
var tblHtml="";
$.each(data.DepotDetailsList,function(a,b){
tblHtml+= "<tr><td>"+b.DepotID+"</td>";
tblHtml+= "<td>"+b.ColumnName+"</td>";
tblHtml+= "<td>"+b.Country+"</td>";
tblHtml+= "<td>"+b.CountryCode+"</td>M/tr>";
});
$("#Grid > tbody").html(tblHtml);
},
Since you already have the partial view which build the table, you can do this.
In your ajax success method call a controller action by passing this data received from the API. The controller will just return the existing partial view by passing the same model.
$.ajax({
url: "/api/Admin/GetDepotDetails/",
type: "POST",
data: { "selectValue": selectValue },
dataType: "json",
success: function (data) {
//$("#Grid").html($(data).children());
$.get("controller/Action",data.DepotDetailsList ,function(response){
$('#tableHolder').html(response) //have a div in your main view which will hold the table. Now the partial view has to be replaced into this div.
});
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
alert(textStatus, errorThrown, jqXHR);
}
});
So as I said, Create a new MVC action method and return a the same partial view by passing the model sent from ajax.
OR you can user Jquery and build the table again - But this is a pain if the table HTML is large (with css, attributes, dynamic arributes etc). - I think the other answer already has the details on this
I'm trying to List items from DynamoDB local to html table using node.js and express,
DynamoDB data goes like this:
{"Items": [{ "id": "A004","name": "ACC LR2","userId": ["1","2","3","4"], {"id": "0001","name": "ABG IT","userId": [ "8","9","10","11"]}}]}
My nodejs routes goes like this:
router.get('/groups', function(req, res, next) {
var params = {
TableName: 'userGroup',
};
dynamodb.scan(params, function(err, data) {
if (err) {
console.log(err);
}
else {
console.log("These are Groups: "+ console.log(JSON.stringify(data.Items)));
res.render('groups',{_uG : data.Items});
}
});
});
my table on the html goes like this:
<table>
<thead>
<th>Id</th>
<th>name</th>
<th>user id</th>
</thead>
<tbody>
<% for(var i = 0; i < _uG.length; i++) { %>
<tr class="gradeA even" role="row">
<td class="sorting_1"><%= _uG[i].id.S %></td>
<td><%= _uG[i].name.S %></td>
<td><%= _uG[i].userId[i].L %></td>
</tr>
<% } %>
</tbody>
</table>
console.log shows results like this:
{"id":{"S":"A004"},"name":{"S":"ACC LR2"},"userId":{"L":[{"S":"7"},{"S":"8"},{"S":"9"},{"S":"10"},{"S":"11"}]}}
I am able to list items of id and name , but I'm not able to list userID , what do I do to list userID on the html table?? .. help is appreciated ..
It looks like userId is an Array of Objects so you need to iterate over it and get the string value of each object. So I would change the line where you render the userId to something like this:
<td><%= _uG[i].userId.L.map(function(item) {return item.S;}).join('') %></td>