Refresh a specific portion of an HTML template following a successful AJAX request

I am facing a challenge in implementing a new feature and I'm unsure of the best approach to take. In my project, I utilize Django for backend logic and templating, as well as the Google Closure JavaScript library for frontend development.

Here is the scenario I need assistance with:

I use a "rate" value to calculate the Total Amount for various entities displayed in a tabular format like this:

<!-- 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 used to calculate the total amount comes from a database table. However, I need to explore different scenarios by changing the rate and calculating the resulting total amount.

To input a new rate, I have provided an input box as shown below:

<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"/>

When the user clicks the Update Rate button, the updated rate value is stored in local storage. Upon clicking the Recalculate Entities button, an AJAX request will be made to recalculate the values, updating the table with the new information. If the user chooses to reset the rate, the original calculated values will be restored.

While I understand how to send an AJAX request to update the data, I am struggling with re-rendering the table when the "rate" has been modified or reset.

Answer №1

To accurately calculate for a specific entity, you should have a way to identify that entity. Here is an example:

{% 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 %}

Afterwards, in the callback function of the ajax call, update the total value:

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

The actual structure of the returned data may differ, but this framework should guide you in the right direction.

Does this explanation make sense?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it necessary to convert serialized data to JSON before sending a response in Django Rest Framework?

I am really puzzled by the answer to this question. Multiple Models in Django Rest Framework? The answer pertains to sending multiple models in a response, which aligns with my current scenario. The author of the answer presents the following code snipp ...

Passing an HTML5 video element as a prop in Vue.js

I am attempting to pass an HTML5 video as a property from a parent component to a child component in Vuejs. Parent Component: <template> <div> <video ref="video"> <source src="@/assets/video.mp4" type= ...

Use JQuery to load a particular page by specifying its ID with the hashtag symbol

I am facing an issue where I need to create multiple private chatrooms per user. Although I have managed to make it work, I encountered a problem where if there are more than one private chats happening simultaneously, the content of these chats gets broad ...

Migrating to Angular Universal for server-side rendering with an external API server

Thank you for taking the time to read my query. I have developed a project using server-side Node.js and client-side Angular 6. The purpose of the app is to provide information on cryptocurrency prices and details. I am now looking to transition my Angu ...

The action of POSTing to the api/signup endpoint is

Currently delving into the MEAN stack, I have successfully created a signup api. However, when testing it using POSTMAN, I encountered an unexpected error stating that it cannot POST to api/signup. Here is a snapshot of the error: Error Screenshot This ...

What is the best method for eliminating the default title in selectpicker?

I'm currently working on integrating angular selectpicker into my project. Initially, everything was displaying correctly as shown below: <select class="selectpicker"> <option>Mustard</option> <option>Ketchup</opti ...

How jQuery stops the submission of a form

Sample HTML Code <p><select name="status" class="form-control" id="showThisItem"> <option value=""> Select Status </option> <option value="Paid"> Paid </option> <option value="Unpa ...

The video player will only start playing after the source has been changed if it was already in play

I am facing an issue with my video player that has thumbnails. The problem is that the video player does not start playing the selected video unless the video is already playing. This means I have to hit the play button first, and then select the thumbnail ...

The Vue router requires a page reload to see changes and does not have access to the this

When navigating through router-link, the App.vue page opens initially, but the URL changes immediately without displaying the content. Reloading the page is necessary to view it. If you navigate programmatically, you may encounter an error stating 'Ca ...

Utilizing Django's filtering capabilities within the admin interface to customize Model

When navigating to the admin page, I am looking to implement a feature where selecting field_1 will trigger a filtering of field_2 based on the value selected for field_1. Here is the relevant code snippet located in random/models.py: from django.db impo ...

javascriptHow to specify the character set in a Data URI

In a UTF-8 page, I am implementing the following code: var data = "a\tb\tc\r\nd\te\tf"; window.location.href = "data:text/csv;charset=utf-8," + encodeURIComponent(data); This code is used to prompt the browser to download an ...

Bidirectional Relation in Template (Inverse Query)

I'm currently facing a challenge in constructing my own client database involving a reverse lookup feature that just doesn't seem to work as expected: models.py class PersonQuerySet(models.QuerySet): def employees(self): return self ...

Why is it not performing as expected when removing all non-numeric elements from the array?

let arr = [1, "5", 3, 27, undefined, { name: 'Steven' }, 11]; for (let i = 0; i < arr.length; i++) { if (typeof arr[i] !== 'number') { arr.splice(i, 1); } } console.log(arr); // result: [1, 3, 27, {…}, 11 ...

Adding an item to an array in Angular 2 using JavaScript!

In my Angular2 form, I have a field that consists of an array of objects. I've successfully created a table with a Delete Row button for each row and an Add Row button using the push() and slice() methods in JavaScript. However, there's a major ...

Creating JavaScript objects through function calls

let getBoxWidth = function() { this.width=2; }; alert(getBoxWidth.width); Hello there! Can you explain why the output is undefined in this scenario? ...

How can I modify the value of a CSS animation rule in AngularJS?

I am looking to dynamically change the value assigned to stroke-dashoffset based on a custom input. @-webkit-keyframes donut-chart-1 { to { stroke-dashoffset: 100; } } @keyframes donut-chart-1 { to { stroke-d ...

The mystery of the missing cookie in a web application built with AngularJS, Django,

I've recently started developing an AngularJS application that uses Django Rest Framework and Django CORS Headers for the backend API. Initially, everything was functioning correctly, but today I encountered an issue where the csrfcookie and sessioni ...

How can a JavaScript array be transmitted as a JSON value?

Is there a method to pass a JavaScript array as a JSON variable in my AJAX query? ...

Is there a more efficient method for implementing React OnChange for each field?

When calling an API, receiving a payload and loading it into state in React, we often encounter situations where we have multiple fields to update. This can lead to creating numerous onChange functions for each field. Is there a more efficient pattern tha ...

What is the reasoning behind jQuery UI employing CSS classes as opposed to pseudo-classes?

In this detailed explanation found on this website, it is discussed why jQuery UI uses CSS classes like .ui-state-active that are applied through JavaScript, rather than utilizing existing CSS pseudo-classes like :active. What is the reasoning behind thi ...