2

I found a code here to change the table content dynamically

The script is in jQuery

Original jQuery code to change the table content dynamically

$(document).ready(function(e) {

    var data1 = [
        { field1: 'value a1', field2: 'value a2', field3: 'value a3', field4: 'value a4' },
        { field1: 'value b1', field2: 'value b2', field3: 'value b3', field4: 'value b4' },
        { field1: 'value c1', field2: 'value c2', field3: 'value c3', field4: 'value c4' }
        ];

    var data2 = [
        { field1: 'new value a1', field2: 'new value a2', field3: 'new value a3' },
        { field1: 'new value b1', field2: 'new value b2', field3: 'new value b3' },
        { field1: 'new value b1', field2: 'new value b2', field3: 'new value b3' },
        { field1: 'new value c1', field2: 'new value c2', field3: 'new value c3' }
        ];

    function loadTable(tableId, fields, data) {
        //$('#' + tableId).empty(); //not really necessary
        var rows = '';
        $.each(data, function(index, item) {
            var row = '<tr>';
            $.each(fields, function(index, field) {
                row += '<td>' + item[field+''] + '</td>';
            });
            rows += row + '<tr>';
        });
        $('#' + tableId + ' tbody').html(rows);
    }

    loadTable('data-table', ['field2', 'field1', 'field3'], data1);

    $('#btn-update').click(function(e) {
        loadTable('data-table', ['field2', 'field1', 'field3'], data2);
    });

});

I have a similar code but data content is

like 'rollno','name', 'state', 'city','class', 'age'

[
 { 'rollno': 'value a1', 'name': 'value a2', 'state': 'value a3', 'city': 'value a4', 'class': 'value a5', 'age': 'value a6' },
 { 'rollno': 'value b1', 'name': 'value b2', 'state': 'value b3', 'city': 'value b4', 'class': 'value b5', 'age': 'value b6' },
 { 'rollno': 'value c1', 'name': 'value c2', 'state': 'value c3', 'city': 'value c4' , 'class': 'value c5', 'age': 'value c6'}
 ];

instead of

[
 { field1: 'value a1', field2: 'value a2', field3: 'value a3', field4: 'value a4' },
 { field1: 'value b1', field2: 'value b2', field3: 'value b3', field4: 'value b4' },
 { field1: 'value c1', field2: 'value c2', field3: 'value c3', field4: 'value c4' }
 ];

My code

function get_student_filters() {
    var selected_city = document.getElementById("student_city_selected").value;
    var selected_state = document.getElementById("student_state_selected").value;
    var selected_class = document.getElementById("student_class_selected").value;

    var selected_student_filter_data = {
        s_city:selected_city,
        s_state:selected_state,
        s_class:selected_class
    };
    $.ajax({
          type: "POST",
          contentType: "application/json;charset=utf-8",
          url: "http://127.0.0.1:5000/filter_student",
          traditional: "true",
          async:false,
          timeout: 40000,
          data: JSON.stringify({selected_student_filter_data}),
          dataType: "json",
          success: function(selected_student){

            var selected_student_data = JSON.stringify(selected_student)

            // Recevied data from the flask of the selected data from the table
            $(document).ready(function(selected_student_data) {

                // Function to fill the table
                    function loadTable(tableId, fields, data) {
                        // $('#' + tableId).empty(); //not really necessary
                        var rows = '';
                        $.each(data, function(index, item) {
                            var row = '<tr>';
                            $.each(fields, function(index, field) {
                                row += '<td>' + item[field+''] + '</td>';
                            });
                            rows += row + '<tr>';
                        });
                        $('#' + tableId + ' tbody').html(rows);
            // call function to populate the table
            loadTable('studetnt_table', ['rollno','name', 'state', 'city','class', 'age'], selected_student_data);
                    }
          }
          });
}

Nothing gets printed on the table

Two issues

1) Data that i received is not in the same syntax as in the snippet

2) I don't know if $(document).ready(function(selected_student_data) jQuery will work inside js script as i have written above

Could anyone please guide me here

PS This is not on button click but on the option that the user selects for the drop down of the column in city ,class and state How to make dropdown list filter for a table using jQuery?

2
  • The data looks exactly the same to me: it doesn't matter if there is quotes around your key in your object: they don't make a difference in your case. Commented Nov 22, 2019 at 13:31
  • @Terry How do i populate the table, if there is no issue data field? I have updated it now Commented Nov 22, 2019 at 14:25

2 Answers 2

1

There are a lot of mistakes in your code.

  • Don't do JSON.stringify({selected_student_filter_data}) unless your server expects an object with a selected_student_filter_data property. That's ES2015 Object Property Shorthand.
  • Don't put $(document).ready inside the AJAX success response, have the function loadTable outside and call it from there and once from $(document).ready.
  • selected_student_data = JSON.stringify(selected_student) will put a string value for selected_student_data. You don't wanna do that. You need JSON.parse but jQuery will do that for you if you set the response header Content-type: application/json.

I suggest you first wipe out everything inside success function and just check and understand if you get correct data and in what form. Then create the function loadTable that will populate the data to the table.

...
success: function(data) {
  console.log(data); // Open console and check the data you get
}
...
Sign up to request clarification or add additional context in comments.

1 Comment

JSON.parse doesn't work, JSON.stringify gives the data in the above mentioned format.
0

If you don't mind different implementation, Check the following solution.

Dynamically renders the table content.

function addTable(data, headers) {

  var myTableDiv = document.getElementById("myTable");
  myTableDiv.innerHTML = "";

  var table = document.createElement('TABLE');
  table.border = '1';

  var tableHeader = document.createElement('THEAD');
  table.appendChild(tableHeader);

  var tableBody = document.createElement('TBODY');
  table.appendChild(tableBody);

  var n = data.length;
  var m = headers.length;
  var thKeys;
  if (n > 0) {
    thKeys = Object.keys(data[0]);
  }

  var tr = document.createElement('TR');
  tableBody.appendChild(tr);

  for (var j = 0; j < m; j++) {
    var td = document.createElement('TD');
    td.width = '75';
    td.innerText = thKeys[j];
    tr.appendChild(td);
  }


  for (var i = 0; i < n; i++) {
    tr = document.createElement('TR');
    tableBody.appendChild(tr);

    for (var j = 0; j < m; j++) {
      var td = document.createElement('TD');
      td.width = '75';
      td.innerText = data[i][thKeys[j].toLowerCase()];
      tr.appendChild(td);
    }
  }

  myTableDiv.appendChild(table);

}

var data = [
  {
    "title": "021",
    "score": 86,
    "ref": "desc 021",
    "id": "ABC021"
  },
  {
    "title": "022",
    "score": 72,
    "ref": "desc 022",
    "id": "ABC022"
  }
];

addTable(data, ['Title', 'Score']);

function updateTable() {
  addTable(data, ['Title', 'Score', 'Ref', 'Id']);
}

function reset() {
  addTable(data, ['Title', 'Score']);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="myTable"></div>

<button onclick="updateTable()">update table</button>

<button onclick="reset()">reset table</button>

Comments

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.