javascriptajaxdjangodjango-templatesgoogle-closure

Rerender a HTML template fragment or section after a successful AJAX post


I am trying to implement a feature and I have no idea how to go about it. My project leverages Django to implement backend logic and templating and Google Closure javascript library for front end.

My use case is given below:

I use a "rate"value to calculate the Total Amount for numerous entities. The entities are displayed in tabular format as follows:

<!-- I need to reload this table again.  -->
<table class = "striped" ....>
 <thead>
   <tr>
      <th>Entity</th>
      <th>Amount (USD)</th>
      <th>Rate (%)</th>
    </tr>
  </thead>
  <tbody>
     {% for entity in entities %}
     <tr>
        <td>{{ entity.name }}</td>
        <td>${{ entity.total }}</td>
        <td>{{ entity.rate }}</td>
     </tr>
    {% endfor %}
  </tbody>
 </table>

The rate is available in the database table to calculate the total amount. But I have to do the following "what-if" scenario; What would the total be if the "rate" was changed?

I have an input box that accepts new rate as follows:

<label for="Updated Rate">
<input type=number id="updatedRate" name="updatedRate" value="0" />
<input type="button" value="Update Rate" />
<input type="button" value="Recalculate Entities"/>
<input type="reset" value="Reset rate and Recalculate"/>

I store the update rates value to windows local storage when the user clicks the Update Rate button, then. If the user clicks the Recalculate Entities button, then I would like to make a AJAX request to the back end to recalculate the updated value and re render the table with the updated values. If the user resets the rate value, then the recalculated values must be In this event, the rate used would be fetched from the database and the table would have to re rendered.

I know how to make a AJAX request to the back end to recalculate the data.but I don't know how to re render the table if the "rate" has been updated or reset.


Solution

  • You need a way to identify the entity you are calculating for. Something like:

    {% for entity in entities %}
     <tr data-id="{{ entity.id }}">
        <td>{{ entity.name }}</td>
        <td class="total">${{ entity.total }}</td>
        <td>{{ entity.rate }}</td>
     </tr>
    {% endfor %}
    

    Then in the callback of the ajax replace the total:

    $.ajax({
      url: 'someurl',
      success: function(json) {
        $('tr[data-id=' + json.id + '] td.total').text(json.total);
      }
    });
    

    Of course the actually structure of the returned data will vary. But I think you've got the basic structure.

    That help?