3

In my project I'm using Parse.com as server and database, and DataTable plugin to create a table showing the data returned. There's no problem when I use a predefined json file, but when I try to construct a local json file using the data returned from Parse.com I get an error. It seems no matter what I do, the table creation process is run first and only afterwards the json object is created.

JSfiddle with the relevant code is here. Please note that due to the large amount of code I did not provide a working sample, but only the relevant part.

function getDataFromParse(){
    console.log("test function run");

       var loc_json={
          "data":[]
      };
                        //get data from parse
              var parseTable = Parse.Object.extend("parseTable");
                var tableObj = new parseTable();
              var query = new Parse.Query(parseTable);
              var count=0;

              query.descending("createdAt");
              query.find({
                  success: function(resultArr){
                                console.log("retreiving data from parse");
                        for(var i=0;i<resultArr.length;i++){
                                query.get(resultArr[i].id,{
                                  success: function(tableObj){
                                    var ret_phone = tableObj.get("phone");
                                      var ret_first = tableObj.get("firstName");
                                      var ret_last = tableObj.get("lastName");
                                      var ret_status = tableObj.get("redemption_status");
                                      var ret_vipCode = tableObj.get("vipCode");

                                      loc_json.data.push([count,ret_first +" "+ret_last,ret_phone,tableObj.get("createdAt"),ret_vipCode]); //construction of local json
                                      count++;
                                      console.log("finished fetching data for "+ret_first+" "+ret_last);
                                  },
                                  error: function(object, error) {
                                        console.log("could not do something "+error.message);
                                  }
                                });
                        }
                      console.log("success function end");
                  },
                  error: function(error){
                      console.log(error.message);
                  }
              });
    console.log("trying to return json");
    return loc_json;
}  



    var rows_selected = [];
    console.log("table creation");
    var table = $('#example').DataTable({
      ajax: getDataFromParse(),       // ajax: 'https://api.myjson.com/bins/4qr1g', THIS WORKS!!
      columns: [
        {},
        { data: 1},
        { data: 2 },
        { data: 3 }
      ],
      'columnDefs': [{
        'targets': 0,
        'searchable':false,
        'orderable':false,
        'className': 'dt-body-center',
        'render': function (data, type, full, meta){
          return '<input type="checkbox">';
        }
      }],
      'order': [1, 'asc'],
      'rowCallback': function(row, data, dataIndex){
        // Get row ID
        $('input.editor-active', row).prop( 'checked', data[3] == 1 )
        var rowId = data[0];

        // If row ID is in the list of selected row IDs
        if($.inArray(rowId, rows_selected) !== -1){
          $(row).find('input[type="checkbox"]').prop('checked', true);
          $(row).addClass('selected');
             console.log("table trying to create itself");
        }
      }
    });
2
  • 1
    Added jQuery and Parse.com CDN but getting "Uncaught Error: You need to call Parse.initialize before using Parse." I'm guessing because there are no "APPLICATION ID" or "JAVASCRIPT KEY". Perhaps set up a dummy project and add an ID and Key? There also needed to be a table with the id of example... (jsfiddle.net/annoyingmouse/t6xj4wks/2) Commented Oct 4, 2015 at 10:45
  • Thanks for the replay, I've created a new app with some sample data in it, and updated your fiddle. it can be found here: jsfiddle.net/t6xj4wks/5 Commented Oct 4, 2015 at 11:24

1 Answer 1

1

SOLUTION

  1. Remove ajax option from DataTables initialization options.

  2. Call getDataFromParse() after initializing the DataTable

  3. In the success handler for each query, replace this line:

    loc_json.data.push([count, ret_first + " " + ret_last, ret_phone, tableObj.get("createdAt"), ret_vipCode]);
    

    with the line below to add a new row to the table.

    $('#example').DataTable()
       .row.add([
          count, 
          ret_first + " " + ret_last, 
          ret_phone, 
          tableObj.get("createdAt"), 
          ret_vipCode
       ])
       .draw(false);
    

DEMO

See this jsFiddle for code and demonstration.

NOTES

  • The drawback of this solution is that a new row would be added once each query finishes successfully. Not sure if it is possible with Parse.com to handle event when all queries are completed.

  • Your example uses jQuery DataTables 1.9 but you're using option names and API from 1.10. You need to upgrade your jQuery DataTables library.

  • You're supplying data to jQuery DataTables using ajax option were in fact you should be using data option instead.

  • Remove code after // FOR TESTING ONLY as it was needed for demonstration only in jQuery DataTables - Row selection using checkboxes article and is not needed for production.
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the elaborated answer. It seems that the table creation function is still executed first, and only afterwards the loc_json is being populated. The console first shows "table creation" message and only then this line is executed console.log("finished fetching data for "+ret_first+" "+ret_last);. Am I missing something?
@undroid, you're right. I missed the code that there are additional asynchronous query.get(), I have updated my solution.
Thanks! It works quite well, now I'm able to receive the data, but the odd thing is that the table is actually shows data only if I click on one of the headers of the table. Seems like it refreshes the table to show the data.
@undroid, I have corrected the code, you need to add draw(false) to update the table after adding each row, see my answer for code.
Perfect. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.