Display data from Firebase database in a HTML page - html

I am new to Firebase and JS.
I am trying to display some user information on a web-page that is stored in Firebase database.
Data format is something as this image:
Based on the image above :
From the available nodes, UserData is the one that holds the name, email, assigned-id
I don't require to show User1/User2/User3, they are unreadable such as HNpTPoCiAYMZsdfdsfDD3SDDSs555S3Bj6X35.
I just need the Values associated with Attr1 and Attr3 for all the users there exists.
Now, I would like to fetch this data and show it in a webpage(one of HTML) in a tabular format.
Name | Assigned ID
___________________
Name 1 | ID 1
Name 1 | ID 2
Name 3 | ID 3
I have seen some tutorials but they weren't clear and helpful.
This is the Javascript code I have written basis some tutorials, and only one record is being displayed from the database, rather than whole -
Also this is the last record available in the database, can i display the same in the sorted order of AssignedID value
(function(){
// Initialize Firebase
var config = {
apiKey: "Aaasff34eaADASDAS334444qSDASD23ASg5H",
authDomain: "APP_NAME.firebaseapp.com",
databaseURL: "https://APP_NAME.firebaseio.com",
storageBucket: "APP-NAME.appspot.com",
messagingSenderId: "51965125444878"
};
firebase.initializeApp(config);
var userDataRef = firebase.database().ref("UserData").orderByKey();
userDataRef.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val(); // childData will be the actual contents of the child
var name_val = childSnapshot.val().Name;
var id_val = childSnapshot.val().AssignedID;
document.getElementById("name").innerHTML = name_val;
document.getElementById("id").innerHTML = id_val;
});
});
}());
Can someone kindly help me achieve this? Thanks in advance.

There are two things you need to change 1. instead of using get element by id use jquery and also so that it doesn't overwrite itself use append to list the select items from the database.
var userDataRef = firebase.database().ref("UserData").orderByKey();
userDataRef.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var name_val = childSnapshot.val().Name;
var id_val = childSnapshot.val().AssignedID;
$("#name").append(name_val);
$("#id").append(id_val);
});
});
This on its own would output your database items one after the other and so to add formatting to every database item you can do things like this (by the way this is why you have to use jquery as this didn't work with the normal js stuff)...
$("#name").append("<p>" + name_val + "</p><p> " + id_val + "</p>
<br>");
This would look like this for every name and id
Name Id
Name Id
Name Id
You could also have used this for entering you data from your database into a table by putting each item in a tag and so on if you don't know what im on about just go learn about html tables and from then on its self-explanatory.

The reason you are only seeing the last item is because of these 2 lines
document.getElementById("name").innerHTML = name_val;
document.getElementById("id").innerHTML = id_val;
You're not creating new items, just writing/overwriting in the same spot. Each item replaces the name/id of the one before until the last item. Consider using element.appendChild() to add the items to an <li> element.
As far as sorting goes, check out this page of the firebase doc: https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
Hope this helps!

Related

How to get Quantities of selected object?

how to get Quantities of selected object, like you can see here: https://imgur.com/71Rm0Y4 ?
#PetrBroz helped me to get Properties of selected object (He's example is here:
) but I also need to get Quantities: https://imgur.com/71Rm0Y4
Thank you.
You'll need to traverse the instance tree to find the parent you're interested in. In your example, it would be something like this:
const ids = viewer.getSelection();
if (ids.length > 0) {
const instanceTree = viewer.model.getData().instanceTree;
let id = ids[0];
id = instanceTree.getNodeParentId(id);
id = instanceTree.getNodeParentId(id);
id = instanceTree.getNodeParentId(id);
// Or better, traverse the parents in a while loop until you find one that matches your requirements
viewer.getProperties(id, function(props) {
console.log(props);
});
}

Indesign - Is it possible to update value in cell when I know ID of the product?

I have a question, my colleague is creating product catalog in our company (in Indesign)
He is updating a version from last year, because we have not much new products BUT all the prices (~7000) are new.
I have never worked with Indesign before, so my question is, is it somehow possible to update OLD prices to NEW prices using ID of products, and the price is always located in the cell next to ID? Please check screenshots.
This is the table with new Prices, in csv file.
THANKS for any help.
Nikol
Possible workaround is:
read CSV line by line and store current ID and current price
use current ID for doc.findText() method
the parent of 1st found element should be an IDcell
odlPriceCell should be a current table's cell with index +1
use current price for new odlPriceCell contents
sample code:
var
mDoc = app.activeDocument,
mSource = File("~/Desktop/prices.csv"),
// mTarget = mDoc.stories.everyItem().tables.everyItem(),
cLine, cID, cPrice,
cFound, oldID_Cell, target_Cell,
separator = ",";
app.findTextPreferences = null;
mSource.open("r");
do {
cLine = mSource.readln().split(separator);
cID = cLine[0];
cPrice = cLine[1];
if (!cID.match(/^\d+-\d+/)) continue;
app.findTextPreferences.findWhat = cID;
cFound = mDoc.findText();
if (!cFound.length) continue;
oldID_Cell = cFound[0].texts[0].parent;
if (oldID_Cell.constructor.name !="Cell") continue;
target_Cell = oldID_Cell.parent.cells.item(oldID_Cell.index + 1);
target_Cell.texts[0].contents = cPrice;
} while (!mSource.eof);
mSource.close();
Notice mSource path to modify

Most efficient way to save JSON data and reuse on next page in JQuery

On my (Cordova, jQuery-Mobile) iOS mobile application I receive some JSON values on the first page.
To store them I use arrays.
To pass them and reuse them on the second page I use a each function, count up an integer(i) on every run and push the received data into several arrays, the integer(i) I store in a DIV in data-id. (<div data-id'"+i+"'>)
As soon as the User navigates to the second page by tapping on one of the DIVs I use the integer(i) in data-id to get every value from the arrays and display on page 2.
Example
Database:
ID NAME SURNAME AGE USERID
1 Michael Douglas 44 uid3242
2 Eric Cartman 11 uid9275
3 Felix Woodspuck 38 uid3852
4 Amadeus Mozart 158 uid1120
Script:
ID = [];
NAME = [];
SURNAME = [];
AGE = [];
USERID = [];
for example - If the user clicks on the DIV with data-id=2
iInt = $(this).attr('data-id'); // iInt=2
$("#abc").text(NAME[iInt];) // NAME[2]; --> Eric
$("#xyz").text(SURNAME[iInt];) // SURNAME[2]; --> Cartman
...
This is just an example, please ignore the values.
But in my App I am using a lot of variables on a lot of pages, and it gets a little messy in code, so what I am wondering about is if there is a more efficent way to save the values I get from JSON to use them on the second page? How do you do it?
Thank you.
I've been tucking the JSON string into localstorage, then pulling it out later and restoring to an object.
localStorage.setItem("jsondata",mytextvar);
Then later:
var obj = JSON.parse(localStorage.getItem("jsondata"));

Creating a user generated list in flash

I'm trying to create a flash application that will keep track of user generated values. The app should basically allow the user to input the name of the item and it's cost. The total costs should then be added up to show a total value to the user. I can probably figure out how to add the values together, but I'm not really sure how to allow the user to create a list and then allow the user to save it. Can anyone point me towards a tutorial or point me in the right direction?
I am using variables to add user inputed numbers to come up with a total. The first problem is that actionscript 3.0 does not allow variables for texts. I just converted it to 2.0 to fix this. The second problem, is when I test the app and put in my values and click submit, I get NaN in the total values field. Is there a reason why it wouldn't add the values?
Here is the code I used for the submit button:
on (release) {
total = Number(rent) + Number(food) + Number(travel) + Number(entertainment) + Number(bills);
}
Am I missing anything?
Can I give the input text instance names and then give them variables? How are some ways to go about this?
Thanks for the help!
Have an object array, say for example
var stack:Array = new Array();
Then push the item name and it's cost to that array when user inputs, like
stack.push({item:AAA, cost:xx});
So that you can generate the list whenever you want with that array.
You have to see how this works in code. A list in actionscript could be stored inside an array, vector, dictionary or even an Object.
Var myList:Array = [];
myList.push({name: "item 1", cost: 5 });
myList.push({name: "item 2", cost: 7.5 });
If you want to grab the 'product' of "item 1" from the list, you have to create a function for that, lets call it getProductByName
function getProductByName(name:String):Object
{
for each(var product:Object in myList)
{
if (product.name === name) return product;
}
return null; // no match found
}
You can call that function like this:
var product = getProductByName("item 1");
trace(product.cost); // 5
And you can alter the product, so lets make it more expensive
product.cost += 1;
trace(product.cost); // 6
Have fun! If you are using classes, you would create one for the product, with public name and cost, and in that case you'de better use a vector, to ensure working with the right type.
This is what fixed the issue for me in action script 3.0:
myButton.addEventListener(MouseEvent.CLICK, addThem);
function addThem(e:MouseEvent)
{
totalField.text = String ( Number(field1.text) + Number(field2.text) + ....);
}
I also had to name the instances appropriately.

AdvancedDataGrid total sum of branch nodes

Introduction:
I have an AdvancedDataGrid displaying hierarchical data illustrated by the image below:
The branch nodes "Prosjekt" and "Tiltak" display the sum of the leaf nodes below.
Problem: I want the root node "Tavle" to display the total sum of the branch nodes below. When i attempted to do this by adding the same SummaryRow the sum of the root node was not calculcated correctly(Every node's sum was calculated twice).
dg_Teknikktavles = new AutoSizingAdvancedDataGrid();
dg_Teknikktavles.sortExpertMode="true";
dg_Teknikktavles.headerHeight = 50;
dg_Teknikktavles.variableRowHeight = true;
dg_Teknikktavles.addEventListener(ListEvent.ITEM_CLICK,dg_TeknikktavlesItemClicked);
dg_Teknikktavles.editable="false";
dg_Teknikktavles.percentWidth=100;
dg_Teknikktavles.minColumnWidth =0.8;
dg_Teknikktavles.height = 1000;
var sumFieldArray:Array = new Array(context.brukerList.length);
for(var i:int = 0; i < context.brukerList.length; i++)
{
var sumField:SummaryField2 = new SummaryField2();
sumField.dataField = Ressurstavle.ressursKey + i;
sumField.summaryOperation = "SUM";
sumFieldArray[i] = sumField;
}
var summaryRow:SummaryRow = new SummaryRow();
summaryRow.summaryPlacement = "group";
summaryRow.fields = sumFieldArray;
var summaryRow2:SummaryRow = new SummaryRow();
summaryRow2.summaryPlacement = "group";
summaryRow2.fields = sumFieldArray;
var groupField1:GroupingField = new GroupingField();
groupField1.name = "tavle";
//groupField1.summaries = [summaryRow2];
var groupField2:GroupingField = new GroupingField();
groupField2.name = "kategori";
groupField2.summaries = [summaryRow];
var group:Grouping = new Grouping();
group.fields = [groupField1, groupField2];
var groupCol:GroupingCollection2 = new GroupingCollection2();
groupCol.source = ressursTavle;
groupCol.grouping = group;
groupCol.refresh();
Main Question: How do i get my AdvancedDataGrid's (dg_Teknikktavles) root node "Tavle" to correctly display the sum of the two branch nodes below?
Side Question: How do i add a red color to the numbers of the root node's summary row that exceed 5? E.g the column displaying 8 will exceed 5 in the root node's summary row, and should therefore be marked red
Thanks in advance!
This is a general answer, without code examples, but I had to do the same just couple of days ago, so my memory is still fresh :) Here's what I did:
Created a class A to represent an item renderer data, extended it from Proxy (I had field names defined at run time), and let it contain a collection of values as it's data member. Once accessed through flash_proxy::getPropery(fieldName) it would find a corresponding value in the data member containing the values and return it. Special note: implement IUID, just do it, it'll save you couple of days of frustration.
Extended A in B, added a children property containing ArrayCollection of A (don't try to experiment with other collection types, unless you want to find yourself examining tons of framework code, trust me, it's ugly and is impossible to identify as interesting). Let B override flash_proxy::getPropery - depending of your compiler this may, or may not be possible, if not possible - call some function from A.flash_proxy::getPropery() that you can override in B. Let this function query every instance of A, which is a child of B, asking the same thing, as DataGrid itself would, when building item renderers - this way you would get the total.
When creating a data provider. Create an ArrayCollection of B (again, don't try to experiment with other collections--unless you are ready for lots of frustration). Create Hierarchical data that uses this array collection as a source.
Colors - that's what you use item renderers for, just look up any tutorial on using item renderers, that must be pretty basic.
In case someone else has the same problem:
The initial problem that everything was summed twice, was the result of using the same Array of SummaryField2 (sumFieldArray in the code) for both grouping fields(GropingField2 tavle and kategori)
The Solution to the main question: was to create a new array of summaryfields for the root node(in my intial for loop):
//Summary fields for root node
var sumFieldRoot:SummaryField2 = new SummaryField2();
sumFieldRoot.dataField = Ressurstavle.ressursKey + i;
sumFieldRoot.summaryOperation = "SUM";
sumFieldArrayRoot[i] = sumFieldRoot;
Answer to the side question:
This was pretty much as easy as pointed out by wvxyw. Code for this solution below:
private function summary_styleFunction(data:Object, col:AdvancedDataGridColumn):Object
{
var output:Object;
var field:String = col.dataField;
if ( data.children != null )
{
if(data[field] >5){
output = {color:0xFF0000, fontWeight:"bold"}
}
else {
output = {color:0x006633, fontWeight:"bold"}
}
//output = {color:0x081EA6, fontWeight:"bold", fontSize:14}
}
return output;
}