Home » Jquery » Using jQuery / javascript, how to properly parse an HTML table to send the contents of each row to be updated into the database

Using jQuery / javascript, how to properly parse an HTML table to send the contents of each row to be updated into the database

Posted by: admin February 22, 2020 Leave a comment

Questions:

I am loading members into a database from a table (the table has been populated from an MS Excel spreadsheet so contains fixed columns and variable rows). The ajax call to write the second row has data from the first row. However, when I add the “alert” the data on each ajax call is correct. How do I ensure that all the data from parsing the row has been retrieved before the ajax call?

    var firstName = '';
    var surname = '';
    $("#wrapper tbody tr").each(function() {
        var row = $(this).index() + 1; // +1 since index is 0 based
        $('td', this).each(function() {
            if (row > 1) {
                var $col = $(this);
                var col = $col.index() + 1;
                var text = $.trim($col.text()); // GET TRIMMED TEXT

                if (col === 1){
                    firstName = text;
                }
                if (col === 2){
                    surname = text;
                }
            }
        });
        if (row > 1) {
            alert("firstName: " + firstName + " surname: " + surname);

            //ajax call to server to add to database

        row++;
    });
How to&Answer:

Looking at you code, looks like you’re sending the last record every request.

I do not recommend to send an ajax request for each row. But if you have to do it, try this:

function getRecords() {
  var records  = [];
  var keyNames = ['firstName', 'surname'];

  $("#wrapper tbody tr").each(function(i) {

    if (i === 0) { 
       return;
    }

    var record = {};
    $('td', this).each(function(j) {
        if (keyNames[j]){
          var text = $.trim($(this).text()); // GET TRIMMED TEXT
          record[keyNames[j]] = text;
        }
    });

    records.push(record);
  });

  return records;
}

function sendRequest() {
  var records = getRecords();
  console.log(records);
  //ajax call to server to add to database
}

sendRequest();

I highly recommend you to send more than one item per time.