1

I want to write a function that first retrieves all account data from my database, and then sorts them into a user-friendly HTML table. There, the user can select some accounts, and change them. Here's my code:

$.ajax({
    url: "./database.php",
    type: "POST",
    data: {
        todo: "adminGetAccountTable",
        b: userInfo["UserId"],
        c: userInfo["Password"],
        session: userInfo["SessionName"]
    },
    success: function(response) {
        $("#loadingIcon").css("display", "none");
        console.log(response);
        if (response !== "No accounts registered") {
            var json = JSON.parse(response);
            var accountsTable = "<table class='w3-table-all' id='accountsTable'><thead><tr><th>&nbsp;</th><th><b class='link link-primary' id='00'>NUTZER-ID&nbsp;</a></th><th><b class='link link-primary' id='01'>ERSTELLDATUM&nbsp;</a></th><th><b class='link link-primary' id='02'>NAME&nbsp;</a></th><th><b class='link link-primary' id='03'>VORNAME&nbsp;</a></th><th><b class='link link-primary' id='04'>E-MAIL-ADRESSE&nbsp;</a></th><th><b class='link link-primary' id='05'>GESAMTSTUNDEN&nbsp;</a></th><th><b class='link link-primary' id='06'>ACCOUNTTYP&nbsp;</a></th></tr></thead><tbody>";
            var index = 0;
            for (var current in json) { // 'json' is the data coming from my database
                accountsTable += "<tr>";
                accountsTable += "<td><input type='checkbox' onchange='toggleSelectedEntry(" + index + ", true);'></td>";
                // More user information gets written here
                index++;
            }
            accountsTable += "</tbody></table>";
            document.getElementById("accountsDiv").innerHTML += accountsTable; // Add the table to the div container
        }
    }
});

The entries all have a unique id (the current index). The function toggleSelectedEntry() then adds/removes the entry from an array that stores all the selected entries.

The only problem is that the browser parses this argument wrong. Instead of parsing 0, 1, 2, 3, 4 and so on, it parses them in a weird order: 0, 4, 1, 2, 3. What's strange is that when executing console.log(accountsTable), the indexes are displayed in the right order. Only once it's written and parsed by the browser, this weird order appears.

Does someone know what could cause this? I can also send more code if that helps, I just didn't want to clutter my question too much.

Edit: Here's the code from database.php that I use to obtain the data:

$stmt = $this->connection->prepare("SELECT UserId, Created, FirstName, LastName, Email, IF(PermissionId = 2, 'Admin', 'Nutzer') AS PermissionString FROM users");
$stmt->execute();
$stmtResult = $stmt->get_result();
$rows = array();
while ($r = mysqli_fetch_assoc($stmtResult)) {
    $rows[] = $r;
}
if ($rows == array()) {
    error_log("Cancelled Interaction: No accounts registered");
    echo("No accounts registered");
    exit;
} else {
    foreach ($rows as &$value) {
        foreach ($value as &$field) {
            $field = utf8_encode($field);
        }
    }
    $outputValue = json_encode($rows, JSON_UNESCAPED_UNICODE);
    echo(utf8_decode($outputValue));
    exit;

This returns something like:

[{"UserId":"61fe559d1dd35\u0000\u0000\u0000","Created":"2022-02-05 11:46:53","FirstName":"Nico","LastName":"Marikucza","Email":"nicomarikucza@googlemail.com","PermissionString":"Admin"},{"UserId":"62041298682a0\u0000\u0000\u0000","Created":"2022-02-09 20:14:32","FirstName":"Peter","LastName":"Marikucza","Email":"marikucza.p@gmail.com","PermissionString":"Nutzer"}]
nicom
  • 21
  • 4
  • 1
    Is `json` an [array](https://stackoverflow.com/q/500504/1169519)? – Teemu Mar 24 '22 at 12:21
  • Apparently you don't have an array with an "index", you have an _object_ with numeric property names. _"What's strange is that when executing console.log(accountsTable), the indexes are displayed in the right order."_ - browsers tend to automatically _show_ objects with the property names in "sorted" order, but that does not reflect the actual order the properties have inside the object. – CBroe Mar 24 '22 at 12:25
  • @Teemu It is an associative array, yes – nicom Mar 24 '22 at 12:28
  • @CBroe I didn't know that... Is there a way I can sort them correctly or at least get the right order through `console.log()`? – nicom Mar 24 '22 at 12:29
  • How did you create the JSON? – CBroe Mar 24 '22 at 12:31
  • Also, it is just a normal array that I use for the selection. For example, if you have entries 3 and 1 selected, the array looks like [3, 1] – nicom Mar 24 '22 at 12:31
  • JavaScrip doesn't have "associative arrays". As CBroe said, you probably have an object, and the order is from the db query. For the first aid you could try to order the the query result (`ORDER BY` in the query string) by the indices before encoding it to JSON. – Teemu Mar 24 '22 at 12:31
  • @CBroe The `json` variable comes from a web request I didn't want to post in to avoid my code from getting too cluttered. I can post it though if you are curious. The array storing the selected entries is not an object, but an array. – nicom Mar 24 '22 at 12:33
  • I will edit my question to add the web request code, one second – nicom Mar 24 '22 at 12:34
  • Please provide an example of the response data, that's the key of all the issues you've. – Teemu Mar 24 '22 at 12:38
  • @Teemu I just uploaded an answer to my question explaining it – nicom Mar 24 '22 at 12:43
  • 1
    Ok, sorry. I will add it to my original question then. Just trying to figure out how StackOverflow works – nicom Mar 24 '22 at 12:45
  • It's not an associative array. Can you check the "this returns something like" to confirm that your data is in the correct/incorrect order? – James Mar 24 '22 at 12:49
  • @James I just noticed that the order of the data I shared does not line up with the `accountsTable` variable. So indeed, it looks like both orders are unmatched. Thank you for the idea! I will try to sort the returned data accordingly and see if that helps – nicom Mar 24 '22 at 12:57
  • Well, as you can see, I figured out the issue myself. Thanks a lot for the ideas you guys gave me! Unfortunately, I'm being told I have to wait for two days to accept my answer, but it does in fact work now. – nicom Mar 24 '22 at 13:06

1 Answers1

1

I figured it out myself (with help from the comments).

I found out I was using a function in JS to sort the data in order of LastName ascending. But this mismatched the output of the database, which led the program to assign the numbers incorrectly. I fixed this by simply ordering the output via MySQL as well:

SELECT UserId, Created, FirstName, LastName, Email, IF(PermissionId = 2, 'Admin', 'Nutzer') AS PermissionString FROM users ORDER BY LastName ASC

nicom
  • 21
  • 4