Getting Correct Child in Firebase Web - javascript

I have the following JS code.
var database = firebase.database();
database.ref().child('server/user-search').once('value', function(snapshot) {
if (snapshot.exists()) {
var content = '';
snapshot.forEach(function(child) {
var val = child.val();
content += '<tr>';
content += '<td>' + val.deviceCodename + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
This is the layout I have. Its the child within user-search. Thanks for the help

You have an extra node "0" between the "user-search" UID and the deviceXXX nodes.
If I make the assumption that this extra node is always "0", you should do something like the following:
var database = firebase.database();
database.ref().child('server/user-search').once('value', function (snapshot) {
if (snapshot.exists()) {
var content = '';
snapshot.forEach(function (child) {
var val = child.val()['0'];
content += '<tr>';
content += '<td>' + val.deviceCodename + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});

Related

Downloading CSV contents via Ajax and PHP

I am trying to download CSV contents via PHP script hosted on the server.
This is the jquery code that executes and creates a table:
$(document).ready(function() {
$("#btnSubmit").click(function(){
$.ajax({
type: 'GET',
url: 'http://mydomaincom/wp-content/uploads/get-csv.php',
data: null,
success: function(text) {
var fields = text.split(/\n/);
fields.pop(fields.length-1);
var headers = fields[0].split(','),
html = '<table>';
html += '<tr>';
for(var i = 0; i < headers.length; i += 1) {
html += '<th scope="col">' + headers[i] + '</th>';
}
html += '</tr>';
var data = fields.slice(1, fields.length);
for(var j = 0; j < data.length; j += 1) {
var dataFields = data[j].split(',');
html += '<tr>';
html += '<td>' + dataFields[0] + '</td>';
html += '<td>' + dataFields[1] + '</td>';
html += '<td>' + dataFields[2] + '</td>';
html += '</tr>';
}
html += '</table>';
$(html).appendTo('body');
}
});
});
});
Contents of get-csv.php file:
<?php
header('Content-Type: text/plain');
$csv = file_get_contents('http://mydomaincom/wp-content/uploads/csv-samples.csv');
echo $csv;
?>
Here is the code for button:
<!-- Begin Button -->
<div class="demo">
<input id = "btnSubmit" type="submit" value="Get It"/>
</div>
<!-- End Button -->
From browser:
I can access http://mydomaincom/wp-content/uploads/get-csv.php - no issues
I can access http://mysitecom/wp-content/uploads/csv-samples.csv - no issues
When I click on button nothing happens.
Thanks
Below I tried to put together a working snippet where you can possibly see how it works when it works ...
$(document).ready(function () {
$("#btnSubmit").click(function () {
$.ajax({
type: 'GET',
// url: 'http://mydomaincom/wp-content/uploads/get-csv.php',
// url: 'https://jsonplaceholder.typicode.com/users', // --> JSON
url: "https://data.cdc.gov/api/views/45um-c62r/rows.csv",
data: null,
success: function (text) {
var fields = text.split(/\n/);
fields.pop(fields.length - 1);
var headers = fields[0].split(','), html = '<table>';
html += '<tr>';
for (var i = 0; i < (headers.length,3); i += 1) {
html += '<th scope="col">' + headers[i] + '</th>';
}
html += '</tr>';
var data = fields.slice(1, fields.length);
for (var j = 0; j < data.length; j += 1) {
var dataFields = data[j].split(',');
html += '<tr>';
html += '<td>' + dataFields[0] + '</td>';
html += '<td>' + dataFields[1] + '</td>';
html += '<td>' + dataFields[2] + '</td>';
html += '</tr>';
}
html += '</table>';
$(html).appendTo('body');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnSubmit">get data</button>
After looking around a bit further I did actually find some publicly available CSV data ("Rates of TBI-related Emergency Department Visits, Hospitalizations, and Deaths - United States, 2001 – 2010" from the U.S. Department of Health & Human Services) and I am now using that to demonstrate the AJAX process.
So, your code basically works. It could be simplified of course but that is not the point. I guess that the problems you encounter with your site are probably CORS-related.

How to reorder columns with Knex?

I am pulling all of my data from an Sqlite3 table using Knex, electron and JavaScript and I wish to reorder the columns either on the Knex query or in the HTML/JavaScript side.
My sqlite3 db has the following header data:
id|Role|Password|Reference
With the following code, the table displays in the following order:
Password|Reference|Role|id
I have attempted to utilize the .orderBy method in Knex and have also attempted to reorder in JavaScript, but I cannot seem to reorder the columns.
The Electron side of things, I have:
ipcMain.on('getUserTable:all', (event) => {
let getUserTable =
knex('User').select(['id','Role','Reference','Password']).orderBy('Role');
getUserTable.then(function(tableData){
newWin.webContents.send("userResultSent", tableData);
});
});
In the HTML side of things, I have:
ipc.on('userResultSent', (event, tableData) => {
var html = '<table>';
html += '<tr>';
for( var j in tableData[0] ) {
html += '<th>' + j + '</th>';
}
html += '</tr>';
for( var i = 0; i < tableData.length; i++) {
html += '<tr>';
for( var j in tableData[i] ) {
html += '<td>' + tableData[i][j] + '</td>';
}
}
html += '</table>';
document.getElementById('db_output_container').innerHTML = html;
});
I wish to be able to query the db so that the array displays in the exact order as in the table.
The problem with your current approach is that object are unordered bags of properties. So it does not matter how order your columns - properties order is not guaranteed.
If you need specific order you could use Array instead.
Since you have general code to display tabular data you could do the following
ipcMain.on('getUserTable:all', (event) => {
const columns = ['id','role','reference','password']
let getUserTable =
knex('User').select(columns).orderBy('role');
getUserTable.then(function(tableData){
newWin.webContents.send("userResultSent", {columns, tableData});
});
});
When creating html
ipc.on('userResultSent', (event, {columns, tableData}) => {
var html = '<table>';
html += '<tr>';
columns.forEach(column => {
// if you want to capitalize names just do it here
html += '<th>' + column + '</th>';
})
html += '</tr>';
for( var i = 0; i < tableData.length; i++) {
html += '<tr>';
columns.forEach(column => {
html += '<td>' + tableData[i][column] + '</td>';
})
html += '</tr>';
}
html += '</table>';
document.getElementById('db_output_container').innerHTML = html;
})
At the end of the second for loop, you should close the tr tag. Indeed, you open it right after the second for loop but you don't close it.
I haven't tested yet but it should work.
Your html file should looks like this.
ipc.on('userResultSent', (event, tableData) => {
var html = '<table>';
html += '<tr>';
for( var j in tableData[0] ) {
html += '<th>' + j + '</th>';
}
html += '</tr>';
for( var i = 0; i < tableData.length; i++) {
html += '<tr>';
for( var j in tableData[i] ) {
html += '<td>' + tableData[i][j] + '</td>';
}
html += '</tr>'; /* i added this line here */
}
html += '</table>';
document.getElementById('db_output_container').innerHTML = html;
});

jQuery Clear Data With Each Form Submission

I have a form where I'd like to allow users to change their inputs. The code below handles the form. I thought that $("tabledata").empty(); would clear it with each submission, but it is not. Instead, the new table is just being appended to the existing.
jQuery(function () {
$('#401k').submit(function (e) {
$("#tabledata").empty();
var salary = [];
var data = $('#401k :input').serializeArray();
currentage = +data[2].value;
retirementage = +data[3].value;
contribution = +data[0].value/100;
salaryincrease = +data[1].value;
tabledata += "<h3>Starting Salary: " + startingsalaryedit + "</h3><h3>401k Match Percentage: " + match + "%</h3>";
tabledata += "<table class=bluetable>";
tabledata += "<tr><th>Age</th><th>Employee Contribution</th><th>Employer Contribution</th><th>Ending Balance (No Contribution)</th><th>Ending Balance (Contributions)</th><th>Ending Balance (Total)</th></tr>";
for (i = currentage; i <= retirementage; i++) {
yearsage = i - currentage;
salary[i] = startingsalary * Math.pow(1+(salaryincrease/100),yearsage);
employeecontribution = (salary[i] * contribution).formatMoney(2,'.',',');
employercontribution = (salary[i] * (match/100)).formatMoney(2,'.',',');
tabledata += "<tr>";
tabledata += "<td>" + i + "</td>";
tabledata += "<td>" + employeecontribution + "</td>";
tabledata += "<td>" + employercontribution + "</td>";
tabledata += "</tr>";
};
tabledata += "</table>";
$("#tabledata").append(tabledata);
e.preventDefault();
});
Problem is you are not declaring
var tabledata = ''
Therefore it is global scoped, and you are just appending to the previous. You can console.log tabledata variable to see.

Firebase update child Javascript

I want to update child status as Active, but I really do not know how to solve this. I want to update a specific record, I am using table btw. I'm stuck here already. Please help me. Thank you!
<script>
// Get a reference to the database service
var database = firebase.database();
database.ref('Users').orderByChild('usertype').equalTo('Property Owner').on('value', function(snapshot) {
if (snapshot.exists()) {
var content = '';
snapshot.forEach(function(data) {
var stat = data.val();
if (stat.status == 'Inactive') {
var val = data.val();
content += '<tr>';
content += '<td>' + val.fname + '</td>';
content += '<td>' + val.mname + '</td>';
content += '<td>' + val.lname + '</td>';
content += '<td>' + val.email + '</td>';
content += '<td>' + val.registered + '</td>';
content += '<td>' + val.status + '</td>';
content += '<td><button type="button" id="button" style="font-size: 12px;class="btn btn-danger" onclick="myFunction()">Update Status</button></td>';
content += '</tr>';
}
});
}
$('#ex-table').append(content);
});
function myFunction() {
alert('');
}
</script>
This is my json tree in firebase.
Ok, let me take a crack at this, what you're trying to do is update a field. You can find info in the docs on how to do so here, but essentially what you need to do is build a reference to the specific user you want to modify, and then call update on it. So, in whatever you have listening to the button, you want to do something like
firebase.database().ref().update({'users/USERNAME/status': "Active"})
Where USERNAME is the name of the specific user you want to update.

Create a table in javascript from returned JSON object by http get

This is the function in my javascript. Triggered by an onclick function by an another function.
function getValueUsingParentTag(){
var tv_type = [];
var screen_size = [];
var connectivity = [];
var features = [];
var chkArray = [tv_type,screen_size,connectivity,features];
$("#tvtype input:checked").each(function() {
tv_type.push($(this).val());
});
$("#screensize input:checked").each(function() {
screen_size.push($(this).val());
});
$("#connection input:checked").each(function() {
connectivity.push($(this).val());
});
$("#feature input:checked").each(function() {
features.push($(this).val());
});
console.log(chkArray);
//alert(JSON.stringify(chkArray));
alert('hello');
$.get("output-tv.php",{tv_type:tv_type,screen_size:screen_size,connectivity:connectivity,features:features},function(chkArray){
});
}
This is the sample json object returned
{"result":[
{"product_code":"B2810","tv_name":"32B2810","size":"32","tv_type":"INTERNET TV"},
{"product_code":"B2610","tv_name":"48B2610","size":"48","tv_type":"INTERNET TV"}
]}
I need to create a table in javascript based on the json object returned. I dont know how. Please Help.
following function builds the table in a string.
function getTable(data) {
var html = "";
html += "<table><tr><td>product_code</td><td>tv_name</td><td>size</td><td>tv_type</td></tr>";
html += "<tr>";
for(var i = 0, ceiling = data.result.length; i < ceiling; i++) {
var row = data.result[i];
html += "<td>" + row.product_code + "</td>";
html += "<td>" + row.tv_name + "</td>";
html += "<td>" + row.size + "</td>";
html += "<td>" + row.tv_type + "</td>";
}
html += "</tr>";
html += "</table>";
return html;
}
suppose you have a div with id mydiv, you can add the table to this div with following code:
document.getElementById("mydiv").innerHTML = getTable(data);
Here's a simple Javascript only loop example:
http://jsfiddle.net/mCLVL/
var tableData = {"result":[
{"product_code":"B2810","tv_name":"32B2810","size":"32","tv_type":"INTERNET TV"},
{"product_code":"B2610","tv_name":"48B2610","size":"48","tv_type":"INTERNET TV"}
]};
var tableHTML = "<table>";
for (var i = 0; i < tableData["result"].length; i++) {
tableHTML += "<tr>";
tableHTML += "<td>" + tableData["result"][i]["product_code"] + "</td>";
tableHTML += "<td>" + tableData["result"][i]["tv_name"] + "</td>";
tableHTML += "<td>" + tableData["result"][i]["size"] + "</td>";
tableHTML += "<td>" + tableData["result"][i]["tv_type"] + "</td>";
tableHTML += "</tr>";
}
tableHTML += "</table>";
console.log(tableHTML);
It will be so simple by using JSRender. I made a fiddle using jsrender template check it.
Using JSRender Fiddle

Categories

Resources