dari1495
dari1495

Reputation: 289

Dynamically generate HTML rows in AJAX

This is a bit tricky to explain, I'll try my best.

I have a website based on Spring that uses static HTML pages with AJAX and jQuery. I want to present some info in an HTML page that will always vary in size.

I have a table such as this: (don't mind the terrible design)

test table

So, depending on the number of countries and users returned from the API, I want to have different number of rows.

I'm currently using a jQuery function to inject the HTML code after submitting this form: enter image description here

Such as this:

$('#stats').submit((event) => {
  event.preventDefault();
  $.ajax({
      url: '/api/stats/' + $(event.currentTarget).serialize(),
      type: 'GET',
      success(msg) {
          // language=HTML
          $('#result').html(`
            <div class="container">
                <h2>Country stats:</h2>
                <div class="panel panel-group">
                    <table>
                        <thead>
                            <tr> 
                                <th>Country</th>
                                <th>Users</th>
                            </tr>
                         </thead>
                         <tbody>
                            <tr> <!-- I want to generate here the right amount of rows -->
                                <td>Test</td>
                                <td>2</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>`);
      },
      error() {
          $('#result').html("<div class='alert alert-danger lead'>ERROR</div>");
      },
  });

The response received from the API looks like this:

{
"countries":
    [{"data":xx,"users":xx},
    {"data":xx,"users":xx}],
"other data":
    [whatever]
}

And so on.

How can I render N rows if N is the size of the countries array?

Upvotes: 0

Views: 122

Answers (2)

Micka&#235;l Leger
Micka&#235;l Leger

Reputation: 3440

One solution could be to build your "html" content in 3 part : the begin of your bloc, a loop for each rows according to the size of the countries array, then the end of the bloc :

$('#stats').submit((event) => {
  event.preventDefault();
  $.ajax({
  url: '/api/stats/' + $(event.currentTarget).serialize(),
  type: 'GET',
  success(msg) {
      // language=HTML

      // The begin of your html bloc
      var result = `
            <div class="container">
                <h2>Country stats:</h2>
                <div class="panel panel-group">
                    <table>
                        <thead>
                            <tr> 
                                <th>Country</th>
                                <th>Users</th>
                            </tr>
                         </thead>
                         <tbody>
                   `;

      // Just get your countries array here and loop, this can be wrong
      $.each(response.countries, function() {
          // build each row as you need
          result += '<tr>' + 
                        '<td>' + this.data + '</td>' +
                        '<td>' + this.users + '</td>' +
                     '</tr>';
      });

      // The end of your html bloc
      result += `              
                    </tbody>
                </table>
            </div>
        </div>
                `;

      $('#result').html(result);
  },
  error() {
      $('#result').html("<div class='alert alert-danger lead'>ERROR</div>");
  },
 });

Is it what your are looking for?

Upvotes: 3

Luke
Luke

Reputation: 1181

I would assign the rest of my HTML to a variable like so:

var html = `<div class="container">
            <h2>Country stats:</h2>
            <div class="panel panel-group">
                <table>
                    <thead>
                        <tr> 
                            <th>Country</th>
                            <th>Users</th>
                        </tr>
                     </thead>
                     <tbody>`;

Then, add your rows:

for(var i = 0; i < msg.countries.length; i++){
    html += "<tr><td>" + msg.countries[i].data + "</td><td>" + msg.countries[i].users + "</td></tr>";
}

Finally, add the end of the HTML and set it to the element:

html += `</tbody>
                </table>
            </div>
        </div>`;
$('#result').html(html);

Hope this helps!

Upvotes: 2

Related Questions