How can I link JSON from firebase to Datatable

How can I link JSON from firebase to Datatable

matcha125matcha125 Posts: 6Questions: 3Answers: 0

html

<div class="row">
              <table id="process-table" class="table table-sm table-hover table-bordered">
                <thead class="table-success"></thead>
                <!-- TABLE DATA IS ADDED BY JAVASCRIPT FUNCTION -->
              </table>
          </div>

Javascript

<script>

document.addEventListener("DOMContentLoaded",function(){

//var param = {};

$('#process-table').DataTable({
    
        ajax: {
                 "url": 'https://io-testbase1.firebaseio.com/Mold.json'  ,   //// <---- Is this usable for datatable?
                 "dataSrc": ""    //// <---- what show I put here ?
                },
     columns: [ 
      
        {"title" : "ID" , data: 'ID'},
        {"title" : "Type" , data: 'Type'},
        {"title" : "Maker" , data: 'Maker' },
        {"title" : "Cavity" , data: 'Cavity'},
        {"title" : "Plate" , data: 'Plate'},
        {"title" : "Insert" , data: 'Insert' },
        {"title" : "SR" , data: 'SR' },
        {"title" : "Wire" , data: 'Wire' },
        {"title" : "Etc" , data: 'Etc' },
        {"title" : "Note" , data: 'Note' }

        ]  

      });

})

</script>

I'm not quite sure what shoud I put in dataSrc value
I searched for solution on google some said, need to JSON.stringify the object from firebase first ?
but I'm not quite sure how can I stringify when it is a URL

also I would like to ask an expert for the next step , how can I update JSON from client-side ?

Thank you

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,341Questions: 26Answers: 4,954

    <---- what show I put here ?

    Depends on what is returned from the server/firebase. Use the browser's network inspector tool to grab a sample to post here so we can take a look.

    The Ajax docs explain the ajax.dataSrc option. See the last example in the ajax.dataSrc docs for a function example.

    Not sure if you will to use a function. If your row data is in an array as described above then you just need to point to the array. If its a different structure then you will need to manipulate to a structure Datatables supports.

    Kevin

  • matcha125matcha125 Posts: 6Questions: 3Answers: 0

    i think my problem is ,I don't know where should I put converter from obj in obj(originally JSON from firebase) to arr in obj(which datatable required)
    any suggestion ?

  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin
    Answer ✓

    The JSON being returned from Firebase is an object containing objects, whereas DataTables expects the outer part to be an array. So ajax.dataSrc can be used as a function to perform that transform:

        ajax: {
          url: 'https://io-testbase1.firebaseio.com/Mold.json',
          dataSrc: function (obj) {
            return Object.values(obj);
          }
        },
    

    Or if you prefer a fat arrow function:

        ajax: {
          url: 'https://io-testbase1.firebaseio.com/Mold.json',
          dataSrc: obj => Object.values(obj)
        },
    

    I've set up a little example here.

    Note that there is an inner Record object in each row's object. If you want to access that for the row rendering, you'd need to again create a loop over that object to create an inner array (unless the keys were always going to be the same - which they aren't in this case).

    Allan

  • matcha125matcha125 Posts: 6Questions: 3Answers: 0

    Thank you so much ,allan . now I can render table from firebase
    ,by the way I try to open your _**example here **_but It can't open (404 Not found) .

    about Record obj. could you please explain more (I'm absolutely beginner in programming) ,
    Should I create a loop inside dataSrc function by using "obj.Record" to create inner array first then return them all together to dataSrc? ,

    matcha

  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin

    I really need to fix that link thing. You browser is probably changing the link to https:// which will cause an error. It should be http:// at the moment.

    Should I create a loop inside dataSrc function by using "obj.Record" to create inner array first then return them all together to dataSrc? ,

    You'd need something like:

    dataSrc: function (data) {
      data = Object.values(data);
    
      for ( var i=0; i<data.length; i++ ) {
        data.Record = ...
      }
    }
    

    I don't just want to give you the answer - hopefully you'll be able to work out what you need in the ... based on what line 2 is doing. But if you struggle, let us know.

    Allan

  • matcha125matcha125 Posts: 6Questions: 3Answers: 0

    Hi , allan . I just figured out your task . It work fine . But I just would like to know , Is it correct or any better way to coding , Thank you again

                         dataSrc: function (data) {
                                  data = Object.values(data);
                                  var CollectRecord = []
    
                                    for ( var i=0; i<data.length; i++ ) {
                                           CollectRecord.push(Object.values(data[i].Record))
                                      }            
                                     return CollectRecord.flat()
                                  }                                
    
  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin

    Looks good. If you wanted to save a line of code or two you could use Array.prototype.map, but I recon that looks okay and is easy to read as it is.

    Allan

  • m98jkm98jk Posts: 1Questions: 0Answers: 0

    I tried many solutions but the best one I found is this :

    var table = $('#example').DataTable({
        columns: [
            { data: 'name' },
            { data: 'age' },
            { data: 'email' }
        ]
    });
    
    var ref = firebase.database().ref('users');
    ref.on('value', function (snapshot) {
        var data = [];
        snapshot.forEach(function (childSnapshot) {
            var childData = childSnapshot.val();
            data.push({
                "name": childData.name,
                "age": childData.age,
                "email": childData.email
            });
        });
        table.clear();
        table.rows.add(data);
        table.draw();
    });
    
  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin

    Looks good! I wonder if it can be shortened a little:

    ref.on('value', function (snapshot) {
      table
        .clear()
        .rows.add(snapshot.val())
        .draw();
    });
    

    The Firebase docs indicate that snapshot.val() would basically return an array similar to what you are building in the forEach. I haven't used Firebase, so I'm not certain, but it might make things a little easier.

    Allan

Sign In or Register to comment.