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

A step-by-step guide on how to use the Google Closure Compiler: a

Is there anyone who could assist me in adding a snippet to the basic process of Google Closure Compiler? I have been trying unsuccessfully to do this via JavaScript code. I am using an example snippet from the official npm page, but when I run it, someth ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

The removal of an object becomes unsuccessful when objects with lower indices have been deleted beforehand

Attempting to construct a multi-layer object representing a program; check out my progress here http://codepen.io/Irish1/pen/lbjdw Imagine adding 3 weeks, each with 3 days, and each day having 3 sessions. Removing these objects is feasible as long as caut ...

What is the reason for IE displaying null when the model does not exist?

Why does IE 11 render 'null' if my model does not exist? For instance: <tr> <td [innerHTML]="model?.prop1 | my-pipe"></td> </tr> Imagine this scenario: When the page loads, a request is sent to the server and the res ...

Clicking on the image "Nav" will load the div into the designated target and set its display to none. The div will

Can someone help me with loading a div into a target from an onclick using image navigation? I also need to hide the inactive divs, ensuring that only the 1st div is initially loaded when the page loads. I've tried searching for a solution but haven&a ...

Can I update a label using ajax from the controller?

Hello everyone, I am facing a challenge in changing the text label coming from my Controller's JsonResult. There are two specific issues that I am encountering: 1) I am having difficulty displaying the text sent from my controller onto my view... ...

Steps to clear a form after submitting it

Hello all, I have a rather complex form that sends a message successfully with an alert after submission. I'm wondering how I can clear the entire form once it has been submitted to make it simple? Below is my HTML Form and JavaScript code. I would l ...

Conceal div elements containing identical information by utilizing jQuery

I'm dealing with a webpage that pulls in a long section of divs from another application. Unfortunately, I can't filter the divs before they appear, but I urgently need to hide any duplicate data within certain values using jQuery. The duplicate ...

Finding a character that appears either once or thrice

In my work on JavaScript regex for markdown formatting, I am trying to match instances where a single underscore (_) or asterisk (*) occurs once (at the beginning, end, or surrounded by other characters or whitespace), as well as occurrences of three under ...

Updating the text box's font color to its original black shade

I have a form that includes dynamic text boxes fetching data from the backend. When a user clicks on a text box, the color of the text changes. Upon form submission, a confirmation message is displayed and I want the text box color to revert back to black. ...

Difficulty surfaced in the React project following relocation to a different device

I'm new to using React and webpack with babel loader in my app. My project was running smoothly until I changed machines. I copied all the files except for node_modules (which I installed with npm install). Now, when I try to run or build the projec ...

How to use JQuery UI sortable to automatically scroll to the bottom of the page

Having trouble with a few sortable tables and here is how I initialized the sortable object: var options = { helper: customHelper, handle: ".moveTargetDeliverables", containment: "#fieldset_deliverables_summary", tolerance: 'pointer&a ...

Adjusting the size of images in a Bootstrap lightbox gallery

I am currently working on a website for an artist, making the galleries a key aspect. The website is built using Bootstrap, with the Lightbox for Bootstrap plugin being used for the galleries. Everything seems to be working well in terms of adjusting the i ...

Dealing with a syntax error in JavaScript (Codecademy)

I have been working my way through the JavaScript course on Codeacademy and for the most part, I've been able to figure things out on my own. However, I've hit a roadblock with my code and can't seem to get it right. Here is the code I&apos ...

Secrets to concealing a Material UI column based on specific conditions?

Recently, I encountered a challenge with my MUI datagrid where I needed to hide a column based on a specific role. Below is the code snippet: const hideColumn = () => { const globalAdmin = auth.verifyRole(Roles.Admin); if(!globalAdmin){ ...

Prevent Scrolling of Body Content within a Specified Div

In my current situation, I am dealing with a large number of divs (over 300) that are being used as part of an interactive background. The issue arises when viewing the page on mobile versus desktop – there are too many divs on desktop, causing excessive ...

Updating a table in Laravel 5.2 by adding a new record using AJAX without the need to refresh the page

My inquiry pertains to a specific issue. I have a straightforward form in Laravel where some fields trigger pop up windows with tables. I aim to enable the popup window to display newly added records without requiring a page reload and reopening the popup ...

The JSON java.sql.SQLException occurs when attempting to execute a Positioned Update that is not

In my attempts to utilize JSON in Java Web development, I encountered an issue when trying to transform a List into a JSONArray using the JSONArray.fromObject() method. The exception thrown is as follows: java.sql.SQLException: Positioned Update not suppo ...

Clearing a Vue.js filter: a step-by-step guide

Below is my Vue Js code where I have successfully implemented a filter to API array elements. However, I am facing an issue when trying to set up a button that clears the filter upon clicking, restoring the page to its original state without any changes. ...

The perplexing actions of Map<string, string[]> = new Map() have left many scratching their heads

I encountered an issue while trying to add a value to a map in my Angular project. The map is initially set up using the following code: filters: Map<string, string[]> = new Map(); However, when I attempt to add a value to this map, it starts displa ...