Getting data in web console, but not in website


#1

Hi,

I´m making a order placement app which is using Firebase to store data. I want to present that data on a website. I want the data of the customer to be presented in a list, and pushed down the list every time a new order comes in (order child is changed in firebase).
I´m getting the data in the web console, but it doesn't update on the site itself.
Here is my code:

var ref = database.ref("users");
  ref.on("value", gotData, errData);
  
  function gotData(data) {
   // console.log(data.val);
   var users = data.val();
   var keys = Object.keys(users);
   //console.log(keys);
  
   for (var i = 0; i < keys.length; i++) {
    var k = keys [i];
    var adresse = users [k].Adresse;
    var navn = users [k].Navn;
    var postnr = users [k].Postnummer;
    var telefon = users [k].Telefon;
    var bestilling = users [k].Bestilling;

    // initialize array
var arr = [
    navn,
    adresse,
    postnr,
    telefon
];

// append new value to the array
arr.push(bestilling);

 document.getElementById('B1').innerHTML = arr;
console.log(arr);

    
   }
  }
  
  function errData(err) {
    console.log("Error");
    console.log(err);
  }

#2

Nice work on using firebase to push and post data!

I would check a few things:

  1. Make sure that document.getElementById('B1').innerHTML = 'testing'; is successful in printing "testing" to your screen.
  2. If so, try this: docuemnt.getElementById('B1').innerHTML = JSON.stringify(arr);.
  3. If that works, you'll want to append each new data that comes in to a list. Your current code looks like it will overwrite the innerHTML of 'B1' every time. You can do that with code like from this answer: https://stackoverflow.com/questions/17773938/add-a-list-item-through-javascript

Hope this helps!


#3

Thank you very much! That helped me out a lot!
I´m wondering though, in the example the newest post is put in the bottom of the list. Is there any way to get the newest post at the top of the list?
Thanks again.


#4

Glad it helped!

You could get the newest post at the top a couple ways:

  1. You could use JavaScript's unshift array method to add a new item to the top of your order list array. Here's a link to the docs it if helps.
  2. You could put all your orders in an array, then sort them any way your like with JavaScript's sort function, then iterate through the sorted array to display them. Check out the docs.

I think the latter will give you more readable code that's easier to modify if needed in the future :thumbsup: