Following an ajax call, the table does not display the newly added record

In my typescript file, I have a set of functions that send an ajax request to add values to the database upon clicking a button.

static bindAddForm() {        
        TaxIndex.showHelperMessage(helperText);
        $("#addTaxForm").submit(e => {
            e.preventDefault();
            if (typeof dataLayer !== "undefined") {
                dataLayer.push({ 'event': "my_acc_tax_entry_add_button_clicked" });
            }
            const taxId = $('#add-tax-input').val();
            const countryCode = $('#dllCountry').data('selected-value');
            if (!taxId || !countryCode) {
                $("#add-tax-input-error").removeClass('hidden');
                return;
            }
            var spinner = $('.page-spinner');
            spinner.startSpinning();
            $("#add-tax-input-error").addClass('hidden');
            $.ajax({
                type: 'POST',
                url: '/account/taxes/AddTax',
                data: {
                    taxId: taxId,
                    countryCode: countryCode
                },
                success(response) {
                    TaxIndex.showNotification(response);                    
                    if (response.IsSuccessful) {
                        $('#add-tax-input').val('');
                        $("#eudoc-no").attr('checked', 'checked');
                    }
                    
                },
                complete: () => {
                    spinner.stopSpinning();    
                }
            });
        });
    }

After receiving a successful response, we trigger the showNotification function which displays a notification box and calls the LoadData method to fetch updated data from the server and refresh the datagrid.

static showNotification(response) {
         var notificationBox = $("#notificationBox");
         notificationBox
             .removeClass('alert-success')
             .removeClass('alert-danger')
             .html(response.Message).show();
         if (response.IsSuccessful) {
             notificationBox.addClass('alert-success');
             console.log('successful response in Show Notifications.');
             TaxIndex.loadData();
         } else {
             notificationBox.addClass('alert-danger');
         }
     }

The LoadData function then triggers generateTable to update the datagrid with the new data.

static loadData() {
            const spinner = $('.page-spinner');
            spinner.startSpinning();
            $.ajax({
                type: "GET",
                cache: false,
                url: "/account/taxes/GetTaxes",
                success: (taxes) => {
                    console.log('taxes length' + taxes.length);
                    spinner.stopSpinning();
                    if (taxes.length === 0) {
                        $('#tblTaxesContainer').addClass('hidden');
                    } else {
                        $('#tblTaxesContainer').removeClass('hidden');
                        TaxIndex.generateTaxTable(taxes);
                    }
                }
            });
        }

Here is the code for generating the datatable:

static generateTaxTable(taxes) {

        $("#tblTaxes").empty();
            $.each(taxes,
            (taxRowIndex) => {
    
                var rowData = taxes[taxRowIndex];
                var row = $("<tr>" +
                    "<td>" + rowData.TaxNumber + "</td>" +
                    "<td class='text-center'>" + rowData.CountryCode + "</td>" +
                    "<td class='text-center'>" + rowData.Status + "</td>" +
                    "</tr>");
                const InvalidTaxStatus = 2;
                if (rowData.StatusId === InvalidTaxStatus) {
                    row.addClass('text-secondary');
                }
                $('#tblTaxes').append(row);
            });
    }

The concern raised is that sometimes after successfully adding a value to the database and calling the LoadData function, the datagrid does not reflect the new value immediately. Only after refreshing the browser can the new value be seen. Any insights on why this might be happening would be greatly appreciated. Thank you.

Answer №1

One possible solution could be to address a potential caching issue by including a timestamp in the request URL to ensure that the cache is refreshed:

$.ajax({
    ...
    url: `/account/taxes/GetTaxes?_=${new Date().getTime()}`,
    ...
});

Another approach could be to consider the timing of when the data is available in the database, and possibly introduce a short delay before reloading the data:

if (response.IsSuccessful) {
    setTimeout(() => {
        TaxIndex.loadData();
    }, 200); // introducing a 200ms delay
}

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

What are the steps to display a graph on a webpage using AJAX in Django?

I'm currently working on developing a weather forecast application, and I have implemented a date input box on the home page. When users enter a date and click submit, a graph displaying temperature data should be displayed. I have set up a URL that r ...

jester: constantly jest navigator's mock & check against userAgent/vendor

Purpose: Need to iterate through different combinations of the userAgent Simulate navigator behavior Execute the test Observation: I simulated the navigator.userAgent, simulation works as planned, first test executes as expected Second simulation is per ...

Using Javascript to incorporate a number into a UInt8Array

I need to insert a 2-byte number (ranging from 0 to 65,536) into a UInt8Array. For inserting a single byte number, I can easily refer to its index in the array like this: let bufarray = new Uint8Array(buffer); bufarray[0] = 1; However, I am unsure of how ...

Inserting additional information and assigning a category following a prosperous AJAX request accompanied by output from php echo

I'm currently working on implementing an AJAX call to my PHP file to send an email once a contact form is submitted. Initially, I had everything functioning properly where the response from PHP was displayed in a div above the form. However, I wanted ...

Chaining multiple ajax calls in jQuery is a powerful technique that allows you

I am looking to execute a series of N ajax requests without causing the browser to freeze, and I intend to utilize the jquery deferred object for this purpose. Below is a sample scenario involving three requests, but in reality, my program might need to h ...

Retrieve the URL of a particular XML document from the server using a PHP script, then dynamically load it into a JavaScript file for further processing

As I work on my website, users have the ability to upload and download files while I generate an XML log with operation details. One page on the site displays a table created by reading this XML log. Everything functioned properly when it was all stored l ...

Utilizing SPServices and jQuery for seamless CORS functionality

Trying to access a SharePoint list from a different domain on a mobile device. Below is the code snippet for a simple get request: $.support.cors = true; $(function() { $().SPServices({ operation: "GetListItems", webURL: "http://myurl.com/project ...

Using ES6 and Typescript, when a button is clicked, apply a class to all TD elements within the button except for the first one. No need for jQuery

A sample table structure is shown below: <table> <tr> <td>1</td> <td>joe</td> <td>brown</td> <td><button onclick="addClasses()">Add Class to add TD's in t ...

Using JSON with a jQuery AJAX function

Hello everyone! I'm relatively new to the world of AJAX and I'm having trouble figuring out what's wrong with my code. I'm creating a form that should display content from a database using autocomplete. I'm attempting to update a ...

When the first Div is clicked, can it move to the end of the list?

I have designed a collapsible tab and I would like to make some modifications. I want it so that when the user clicks on the first tab, it will move to the last position in the collapsible list, and the same should happen for the other tabs as well. For ex ...

PHP Session data not saved when echoing or using print_r during an external ajax call

I cannot seem to figure out why I am having such a difficult time debugging this specific issue, and I'm hoping that someone may have an idea of what I might be doing wrong. My Custom CMS system uses Paragraphs as building blocks that are updated usi ...

Add fresh material to the bottom of the page using Javascript

Hey there, I'm having a bit of trouble with my page where users can post their status. I want the new posts to appear at the bottom after the older posts when the user presses the button. Currently, Ajax is placing all new posts at the top of the old ...

I am unable to access the information from my api link using ajax

Before fetching data from my link (), I tested it in my browser and it worked fine. It returned JSON format, but I encountered an error when trying to access the same link with AJAX. Thank you, Below is the code snippet: <script type="text/javascript ...

Encountering a Laravel error: MethodNotAllowedHttpException without any message following an AJAX request to a resource controller

After updating the values of some models in my database and hitting submit, I encountered the following error message: "message: "", exception: "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException", file: "C:&b ...

Form with Material-UI's FreeSolo AutoComplete feature

Visit this Sandbox for more details In the provided SandBox example, Material AutoComplete is being used as a multiple input with free options. The component is expected to return ["term1","term2","term3"] to Formik, and each string should be displayed as ...

Issue with Ant Design form validation

After reading through the documentation, I attempted to implement the code provided: Here is a basic example: import { Button, Form, Input } from "antd"; export default function App() { const [form] = Form.useForm(); return ( <Form f ...

Is there a method to retrieve and organize all routes and corresponding endpoints in a NestJS application?

When it comes to writing middleware to process requests, I am faced with the issue of excluding certain paths without having to hardcode them manually. To tackle this problem, I came up with an innovative solution: My plan is to create a special decorator ...

When a selection is made in React MUI Virtualized Autocomplete, the autocomplete menu scrolls back to the top

I am currently using reactMUI autocomplete with virtualization because the listbox is expected to contain thousands of items. The virtualization feature works fine, but when I add an onchange function, the listbox automatically scrolls back to the top wh ...

Troubleshooting problem: AJAX autocomplete URL returning XML

I found my code reference here: http://example.com/code-reference if ($hint=="") { $hint="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes-> ...

Using properties to generate a header component in TypeScript

I am currently exploring TypeScript and incorporating it into a project for the first time. I'm encountering a challenge as I am not sure what to call this concept, making it difficult to search for solutions. If someone can provide me with the term, ...