0

I have some kind of error in my javascript that I can't seem to figure out. I am creating objects of cars out of a MySql query. Further I am storing these objects into an array (carArray).

The problem seems to appear once I try to access these objects later on. In this example, I want to present the objects within a table.

function AddTableOfCars(){

// Table headers
var heading = new Array();
   heading[0] = "Merke";
   heading[1] = "Reg.nr.";
   heading[2] = "Sist endret";

// Database connection
var mysql      = require('mysql');
var connection = mysql.createConnection({
   host     : 'db_host',
   user     : 'db_user',
   password : 'db_password',
   database : 'db_name'
});

// Empty array to store cars
var carArray = [];

connection.connect();
var stmt = 'SELECT `VehicleID`,`VehicleMake`,`LicenseNumber`,`IsActive`,`DateChanged` FROM `db_table`';
connection.query(stmt, function (error, rows, fields) {
if (error) console.log(error.code);
else {

 // Loop through query result
 // Create car objects
 // Store car objects in array

 for (var i = 0; i < rows.length; i++) {
   var carObj = new Car(rows[i].VehicleID, rows[i].VehicleMake, rows[i].LicenseNumber, rows[i].IsActive, rows[i].DateChanged);
   carArray.push(carObj);

    }
 }
 });

 connection.end();

 // Table columns
 var table = document.getElementById('car-table');

 for (var i = 0; i < carArray.length; i++) {
   var row             = table.insertRow(i);
   var cellMake        = row.insertCell(0);
   var cellLicense     = row.insertCell(1);
   var cellDateChanged = row.insertCell(2);

   cellMake.innerHTML        = carArray[i].VehicleMake;
   cellLicense.innerHTML     = carArray[i].LicenseNumber;
   cellDateChanged.innerHTML = carArray[i].DateChanged;
 }

// Logs for debugging purposes
console.log(carArray);
console.log(carArray[0]);

}

My console.log(carArray); returns the following within the console:

[]
  0: Car
  1: Car
  length: 2

So far, it seems to add up. However, when I try to access one of the objects within the array using console.log(carArray[0]);, it returns undefined.

Does anyone have any pointers for me at this point. It's most likely just a tiny detail that I have missed. But I have been looking at my code for quite some time now, I am starting to see animals instead of code...

Any help would be greatly appreciated.

  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – JJJ Mar 18 '18 at 15:51
  • See also [Is Chrome's JavaScript console lazy about evaluating arrays?](https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) – JJJ Mar 18 '18 at 15:53
  • A little more instructively, we're accustomed to thinking code executes in the order we see it on the page, from top to bottom, but that callback in the select function executes *after* all the code that appears below it. Do the logging in that callback (or in a function it calls). – danh Mar 18 '18 at 15:58

1 Answers1

0

I think you might be experiencing some Async issues. See if this sorts it:

function AddTableOfCars() {

    let tableHeaders = ["Merke", "Reg.nr.", "Sist endret"];
    let mysql = require('mysql');
    let stmt = 'SELECT `VehicleID`,`VehicleMake`,`LicenseNumber`,`IsActive`,`DateChanged` FROM `db_table`';
    let connection = mysql.createConnection({
        host: 'db_host',
        user: 'db_user',
        password: 'db_password',
        database: 'db_name'
    });
    connection.connect();
    connection.query(stmt, function (error, rows) {
        if (error) {
            console.log(error.code);
        } else {
            let carArray = [];
            rows.forEach(row => {
                carArray.push(new Car(row.VehicleID,
                    row.VehicleMake,
                    row.LicenseNumber,
                    row.IsActive,
                    row.DateChanged));
            });
            buildTable(carArray);
        }
    });
    connection.end();
}

function buildTable(carArray){
    // Table columns
    var table = document.getElementById('car-table');

    carArray.forEach(car => {
        var row             = table.insertRow(i);
        var cellMake        = row.insertCell(0);
        var cellLicense     = row.insertCell(1);
        var cellDateChanged = row.insertCell(2);
        cellMake.innerHTML        = car.VehicleMake;
        cellLicense.innerHTML     = car.LicenseNumber;
        cellDateChanged.innerHTML = car.DateChanged;
    });
}

Note: I couldn't see your use of tableHeaders but I left it in anyway.

pixelscript
  • 392
  • 1
  • 8
  • 1
    Thank you, pixelscript. This approach went much better. And you saved me a lot of frustration. You are right about the headers. These were hard coded within the HTML, in addition to the javascript code. Apologize if you found that to be misleading. – Michael S. Mar 18 '18 at 16:20