0

I have a table with user data. I also have a tab where an admin can add new users. It works but I have to reload the page to see the new row. Of course, I can manually rewrite HTML in my event handler

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
              integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <title>Admin Page</title>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <table class="table table-hover text-center">
                      <thead>
                            <tr>
                                <th scope="col">Name</th>
                                <th scope="col">Last name</th>
                                <th scope="col">Department</th>
                            </tr>
                      </thead>
                      <tbody>
                            <tr>
                                <td>John</td>
                                <td>Doe</td>
                                <td>IT</td>
                            </tr>
                            <tr>
                                <td>Jane</td>
                                <td>Doe</td>
                                <td>HR</td>
                            </tr>
                     </tbody>
              </table>
              <a href="#" class="btn btn-outline-primary" data-toggle="modal" data-target="#add-new-user">Add new user</a>
              <div class="modal" id="add-new-user">
                  <div class="modal-dialog modal-centered">
                      <div class="modal-content">
                          <div class="modal-header">
                              <h3 class="modal-title text-center w-100">Fill in the forms</h3>
                              <button type="button" class="close" data-dismiss="modal">&times;</button>
                          </div>
                          <div class="modal-body">
                              <form>
                                  <div class="form-group">
                                      <label for="name">Name: </label>
                                      <input id="name" name="name" type="text" class="form-control" />
                                  </div>

                                  <div class="form-group">
                                      <label for="last-name">Last name: </label>
                                      <input id="last-name" name="last-name" type="text" class="form-control" />
                                  </div>

                                  <div class="form-group">
                                      <label for="department">Department: </label>
                                      <select id="department" name="department" class="form-control">
                                          <option value="IT">IT</option>
                                          <option value="HR">HR</option>
                                          <option value="accounting">Accounting</option>
                                      </select>
                                  </div>

                                  <input type="submit" class="btn btn-primary d-flex ml-auto" value="Submit" />
                              </form>
                          </div>
                      </div>
                  </div>
              </div>
          </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
$(document).ready(function () {
$('form').on('submit', async function (event) {
    event.preventDefault();
    $('tbody').append(
    `<tr>
         <td>
             ${$(this).find('[name=name]').val()}
         </td>
         <td>
             ${$(this).find('[name=last-name]').val()}
         </td>
         <td>
             ${$(this).find('[name=department]').val()}
         </td>
     </tr>`
    );
    $(this).closest('.modal').modal('hide');
});
});
    </script>
    </body>
    </html>

but at any rate I don't think it's best practice and it's not very practical if you have rows with lots of data. My rows also have modals within them so you imagine what a pain it would be

In the actual project, the data in the table is pulled from a database

How do (or rather, should) I dynamically change the page content without page (re)loading (or, preferably, manual rewriting of my HTML in event handlers)?

This SO page doesn't answer my question. I examined all suggested "similar" questions so if it turns out to be a duplicate, it's not because I was lazy. Please keep it in mind

  • 1
    In cases like this, I typically have a function on my backend that returns the html in question and then I use that function both when loading the page in the first place and to return the html fragment when updating via AJAX. – mykaf Apr 12 '23 at 15:01
  • @mykaf do you think you can elaborate on that? Maybe, you can provide some code snippets to illustrate your point, can't you? – Sergey Zolotarev Apr 12 '23 at 16:05
  • This is why React, Vue, and other data-driven libraries exist. Updating the DOM dynamically and efficiently is complicated. That said, your question is too broad. Please see [ask]. – isherwood Apr 12 '23 at 16:19
  • Your link is broken (malformed URL). Please fix that, and [never link "this"](https://www.smashingmagazine.com/2012/06/links-should-never-say-click-here/). – isherwood Apr 12 '23 at 16:20
  • By the way, why doesn't that manual row insertion work? – Sergey Zolotarev Apr 12 '23 at 16:40
  • @Sergey Which part doesn't quite make sense? Code snippet would be somewhat involved since it requires server side code too (I use Coldfusion). 1.) load original html, using backend function(s) to build/style updateable elements. 2.) Use AJAX to update data as needed, calling same function(s) as before to send updated elements back to the client. 3.) replace original element with updated element using JS. – mykaf Apr 12 '23 at 18:12
  • I discovered that my traversing was wrong. Simply targetting `` (without calling `closest()`) made the code snippet work (not best practice if you have multiple `` elements). It's not really relevant but still – Sergey Zolotarev Apr 12 '23 at 21:20
  • I found out that manually rewriting the HTML is monumentally stupid and laborious. Any given row in my table has too many dynamic elements. I began replacing them by first retrieving a row's `.html()` and then calling `replace()` on it, but, oh boy, was it a nightmare. It would've been at least somewhat feasible if I at least didn't have those buttons – Sergey Zolotarev Apr 13 '23 at 01:45
  • Every row has an Update, Disable/Enable and Delete buttons as seen [here](https://stackoverflow.com/questions/75991284/jquery-scripts-dont-reckon-with-the-changes-in-html-how-come) – Sergey Zolotarev Apr 13 '23 at 01:52
  • I tried doing it the dumb way (copypasting entire blocks of code), but I now face another issue. `append()` appends the passed string as it is, including whitespace. It causes problems since there is, for example, a "new_user" user in the database, but no " new_user" user. Is there some `appendIgnoreWhiteSpace()` method? Without whitespace and line breaks the code inside the `append()` argument would become unreadable – Sergey Zolotarev Apr 13 '23 at 21:38
  • What does the offending code with whitespace look like? I'm not quite following how whitespace is causing problems. – mykaf Apr 14 '23 at 14:10
  • @mykaf This, for example, works: `user.username`. But if I make it multiline (I can't show it here in the comments), multiple spaces prepend the value and that value no longer represents an object in the database. Long story short, you may get an SQL exception if you take that username and include it in your database requests. But don't worry, I already removed that whitespace, and it didn't make the code as unreadable as I feared (though, it's still dumb copypaste which I'm a bit embarrassed about) – Sergey Zolotarev Apr 14 '23 at 21:27

0 Answers0