Insert JSON data into rendered template after AJAX call I have an already rendered template and I want to update it with some JSON data I obtain via AJAX.

The template as it is before rendering looks like this (using jinja2 template engine):

&lt;table&gt;
&lt;thead&gt;
    &lt;th&gt; Time &lt;/th&gt;
    &lt;th&gt; Destination &lt;/th&gt;
    &lt;th&gt; Bus number &lt;/th&gt;
&lt;/thead&gt;

&lt;tbody id="table-body"&gt;
{% for bus in buses %}
&lt;tr&gt;
    &lt;td&gt; bus[0] &lt;/td&gt;
    &lt;td&gt; bus[1] &lt;/td&gt;
    &lt;td&gt; bus[2] &lt;/td&gt;
&lt;/tr&gt;
{% endfor %}
&lt;/tbody&gt;
&lt;/table&gt;


And I want to send AJAX requests to update the buses var with new values. The way I do it is deleting the tbody content when new data arrives, and rendering everything again with the new data.

function executeQuery() {
    $.ajax({
        method: 'get',
        url: '/data/json',
        data: { bus_id : {{ bus_id }} },
        success: function(data) {
            data = JSON.parse(data);
            $('#table-body').html('');
            for (i in data){
                $('#table-body').append(
                    "&lt;tr&gt;" +
                    "&lt;td&gt;" + data[i][0] + "&lt;/td&gt;" +
                    "&lt;td&gt;" + data[i][1] + "&lt;/td&gt;" +
                    "&lt;td&gt;" + data[i][2] + "&lt;/td&gt;" +
                    "&lt;/tr&gt;");
                };
        }
      });


How can I improve this code? (FWIW I'm using Flask)
If you're using a jQuery collection more than once, make sure to set a variable, this means you don't have to do unnecessary DOM lookups:

 var $table = $('#table-body');


You can probably improve your append code to make it more legible. Personally I prefer utilising the jQuery methods where possible, such as .text(). 

 data = JSON.parse(data);
 $table.empty(); // empty is more explicit
 // iterate over the data
 data.forEach(function (buses) {
   // create a new table row and append it
   var $row = $('&lt;tr&gt;')
     .appendTo($table);
   // iterate over the buses
   buses.forEach(function (bus) {
     // create the cell, set the text, 
     // and append it to the row
     $('&lt;td&gt;')
       .text(bus)
       .appendTo($row);
   });

 });


Since you're just doing a simple get, you can use jQuery shorthand $.get function:

$.get('/data/json', { bus_id : {{ bus_id }} })
  .success(function (data) {
    // do render
  });