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) %>);
Related
I have a data table which displays 'Name' field and 'Address' field (Address related to another object). The 'Name' field is displayed properly but if I iterate over the list in html for pcon.Address__r.Name it gives error. If only pcon.Address__r is given , it shows [object object] in table. Can anybody resolve this issue?
HTML:
<table class="slds-table slds-table--bordered">
<thead>
<tr>
<th style="background-color: #151963;color: white;">Name</th>
<th style="background-color: #151963;color: white;">Address</th>
</tr>
</thead>
<tbody>
<template for:each={pconfig} for:item="pcon" for:index="i">
<tr class={pcon.row} data-id={pcon.Id} data-index={i} key={pcon.Id} onclick{getquotes} >
<td>{pcon.Name}</td>
<td>{pcon.Address__r.Name}</td>
</tr>
</template>
</tbody>
</table>
</lightning-layout-item>
JS:
#wire(Vendor_getProduct,{ basketId: 'fef0E0000dwedjh' })
getProducts({error,data})
{
if(data)
{
//console.log( 'Fetched Data ' + JSON.stringify( data ) );
this.pconfig = JSON.parse( JSON.stringify( data) );
console.log('products are:',data);
}
else if(error){
this.error=data;
console.log('error is undefined');
}
}
class:
public class c {
#AuraEnabled(cacheable=true)
public static List<Product_Configuration__c> getProduct (Id basketId) {
return [select id,
name,
Address__r.name,
from Product_Configuration__c
where Product_Basket__c =:basketId];
}
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)
I got response from my api it simple one record from my database.
getFilledForm() {
const reservation = this.hotels[0].reservation;
this.accidentFormService.getAccidentForm(reservation).subscribe(
res => {
this.form = res;
console.log('this.form: '+JSON.stringify(this.form));
this.test = Object.keys(this.form).map(key => ({ type: key, value: this.form[key] }));
console.log('this.test: ' +this.test);
},
error => {
console.log(error);
}
)
}
this.form is a object and output looks like:
this.form: {"id":1,reservation":1234,"hotel_name":"BB Hotels"}
I tried to make an array but my array of objects looks like ( this.test )
this.test: [object Object],[object Object],[object Object]
after stringify
this.test: [{"type":"id","value":1},{"type":"reservation","value":null},{"type":"hotel_name","value":"BB Hotels"}]
I want output like: "id":1 no "type":"id","value":1
How sould it be ? I want to make a table from output using *ngFor
-Edit
Added HTML
<table *ngIf="checkForm" class="table table-sm align-items-center table-hover table-flush responsive">
<thead class="thead-light">
<tr>
<th scope="col" class="lPart">ID</th>
<th scope="col" class="lPart">Hotel Name</th>
</tr>
</thead>
<tbody>
<tr
*ngFor="let form of form | paginate: { itemsPerPage: 10, currentPage: p }; let i = index">
<td id="lPart">{{ form.id }}</td>
<td id="lPart">{{ form.hotel_name }}</td>
</tr>
</tbody>
</table>
I'm trying to call my api to get the name of a tp but in the view I only see a [object promise] and in the browser console it looks like it's doing an infinite loop
html:
<table [dtOptions]="dtOptions" class="row-border hover" datatable>
<thead>
<tr>
<th>Date</th>
<th>Intitulé</th>
<th>Résultat</th>
<th>Coefficiant</th>
</tr>
</thead>
<tbody *ngIf="grades?.length != 0">
<tr *ngFor="let grade of grades">
<td>{{ formatDate(grade.Date) | date : 'MM/dd/yyyy hh:mm'}}</td>
<td>{{ getTpName(grade.tp_id) }}</td>
<td><b>{{ grade.Grade | number:'2.1-2' }}/20</b></td>
<td>{{ grade.coeff | number:'1.1'}}</td>
</tr>
</tbody>
<tbody *ngIf="grades?.length == 0">
<tr>
<td class="no-data-available" colspan="4">Aucune note enregistées</td>
</tr>
<tbody>
</table>
TS:
async getTpName(tp_id: any) {
return await this.apiService.getTpName(tp_id);
}
apiservice>getTpName
getTpName(tp_id) {
let url = `${this._tpUrl}/readName/${tp_id}`;
return new Promise((resolve, reject) => {
this.http.get(url, {headers: this.headers}).subscribe(
res => resolve(res),
error => reject(error)
)
});
}
Do you know why it happen and how to correct this ?
EDIT:
It will be good to move the api call from html to component controller.
ngOnInit() {
grades.forEach(grade => {
this.getTpName(grade.tp_id)
.pipe(take(1))
.subscribe(tpName => {
grade.tpName = tpName;
});
});
}
< td > {{ grade.tpName | json }}</td >
Problem
I am making a Meteor.js app, and are importing .csv files via Papaparse.js, which I save in a Mongo collection for later use in a table. The data is saved in a standard Papaparse.js structure:
results = {
data: [ ... ], // parsed data
errors: [ ... ], // errors encountered
meta: { ... } // extra parse info
}
The data array looks like this (from Chrome console):
image
I output this in a front-end view, where this data is shown as a table. But sometimes, the data gets all unsorted. This often happens if I move the DB to another server or import the DB to local. Look at this image for a comparison: image
The question is why, and how I can fix it.
This is my table template:
(note that projectData.data is from Iron Router, which is the Papaparse data (results.data))
<template name="table">
<div class="table-responsive">
<table class="table table-striped table-hover sortable-theme-bootstrap table-fixedheader" data-sortable>
<thead>
<tr>
{{#each addStatusColToArray projectData.meta.fields}}
<th>{{this}}</th>
{{/each}}
<th class="data-controls-header"></th>
</tr>
</thead>
<tbody>
{{#each projectData.data}}
<tr>
{{#each tableObjectToKeyPairs this}}
<td class="{{key}}">
{{value}}
</td>
{{/each}}
<td class="data-controls">
<span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span>
</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
</template>
And this is the corresponding JS file:
Template.embedTable.helpers({
rowClassPropId: function (parentContext) {
var colLink = parentContext.projectData.meta.colLink;
var propId = this[colLink];
return propId;
},
tableObjectToKeyPairs: function (object) {
var filteredObject = _.omit(object, "_id"); // Omit the "_id" value
return _.map(filteredObject, function (value, key) {
return {
key: key,
value: value
};
});
}
});
Template.registerHelper("addStatusColToArray", function (array) {
if (array) {
array.push("Status"); // Pushes the "Status" last into array
return array; // Returns the modified array
}
});