Fresh ajax requests are not clearing the current data displayed in the JSP table

My ajax function retrieves data from a servlet and displays it in the page successfully. However, each time a new ajax call is made, the form appends the new data to the existing results instead of replacing them. I need to reset the current values stored in the OrderResultContainer table before displaying the new data.

I attempted to use the following code:

document.getElementById("OrderResultContainer").reset = (); 

However, this code resets the entire form data and does not display any data on the page.

function addData() {
  if(window.XMLHttpRequest) { 
    var xhttp = new XMLHttpRequest();
    var loading = document.getElementById("loading");
    document.getElementById("loading").style.display = "";
    document.getElementById("OrderResultContainer").style.display = "none";
    xhttp.open("POST","Order",true);        
    var formData = new FormData(document.getElementById('orderform'));
    xhttp.send(formData);
    xhttp.onreadystatechange=function() {            
        if ((xhttp.readyState == 4) && (xhttp.status == 200)) {                 
            var jsonorderdata = JSON.parse(xhttp.responseText);
            txt = "";
            for (x in jsonorderdata) {                  
                txt += "<tr><td>" + jsonorderdata[x].ordernumber+"</td>""</tr>";

             }                                  
            document.getElementById("loading").style.display = "none";              
            document.getElementById("ViewOrderResultContainer").innerHTML = document.getElementById("ViewOrderResultContainer").innerHTML + txt;                
            document.getElementById("divOrderResultContainer").style.display = "";             
        }
          };                
        }else 
        console.log('Ajax call is failed');
}

If anyone can provide guidance on how to specifically reset the data in the OrderResultContainer table after receiving a new ajax response from servlet, it would be greatly appreciated.

Answer №1

To add the new data to the existing data, use the code snippet below:

document.getElementById("ViewOrderResultContainer").innerHTML = document.getElementById("ViewOrderResultContainer").innerHTML + txt; 

If you want to display only the new data without appending it to the existing content, modify the code as shown here:

document.getElementById("ViewOrderResultContainer").innerHTML = txt; 

Answer №2

It may be a bit challenging to understand without the actual html code, but it seems like this is the issue at hand:

document.getElementById("ViewOrderResultContainer").innerHTML = 
document.getElementById("ViewOrderResultContainer").innerHTML + txt;      

Essentially, you are taking the innerHtml from the ViewOrderResultContainer and adding the content of txt to it. If this operation occurs multiple times, the content will keep accumulating. If you intend to replace the text instead, use the following:

document.getElementById("ViewOrderResultContainer").innerHTML = txt;

By the way, note that the provided JavaScript code is not valid:

txt += "<tr><td>" + jsonorderdata[x].ordernumber+"</td>""</tr>";

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

Cloud Function scheduler incorporating dynamic memory allocation control

I am currently working on setting up a scheduled function in Firebase Cloud Functions that interacts with third-party APIs. However, I am facing an issue with the memory limit being exceeded due to the large size of the data processed by this function. Al ...

What is the best way to cycle through a JSON array of objects using JavaScript and jQuery?

Currently, my focus is on understanding JavaScript and JSON objects along with arrays. One of the tasks assigned to me involves iterating through the following array: {"6784": {"OD": [ { "od_id":"587641", ...

Trouble looping through Javascript

Hello, I am encountering a problem with some JavaScript code that I am trying to implement. The functions in question are as follows: var changing_thumbs = new Array(); function changeThumb(index, i, thumb_count, path) { if (changing_thumbs[index]) { ...

Change a space-separated string containing coordinates into an array of JavaScript objects

Here is a string separated by spaces: const coordinates = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604" Now, we want to convert it into an array of objects: const coordinatesArray = [ { lat: 42.44492, lng: 75.637764 }, { lat: 42.4455 ...

What is the best way to incorporate a string value from an external file into a variable in TypeScript without compromising the integrity of special characters?

I am encountering an issue with importing a variable from a separate file .ts that contains special characters, such as accents used in languages like French and Spanish. The problem I am facing is that when I require the file, the special characters are ...

Tips for swapping out a specific string in an HTML webpage with a different string using JavaScript

For my HTML website, I am trying to replace one string with another using JavaScript. Specifically, within the nodeList "AuthorList," there is a string called "Test String" that needs to be changed to "new test." I have attempted various modifications of ...

Having issues with React Nivo tooltip functionality not functioning properly on specific graphs

While using Nivo ResponsivePie to visualize some data, everything is functioning properly except for the tooltip. For some reason, the tooltip isn't appearing as it should. Interestingly, I have a heatmap and a bar graph with tooltips that are working ...

Strange HTML antics

On my website, I encountered an issue when trying to register without entering any information into the required fields. The errors were correctly displayed in this screenshot: However, after inserting random characters into each field and attempting to r ...

Is there a quicker method than using document.getElementById('element-id').innerHTML to retrieve content?

Currently, I am developing a user-friendly step-by-step wizard for my website to gather information about custom orders. Utilizing JavaScript, I have been tasked with updating the content of each "page" using the document.getElementById('element-id&ap ...

Unable to deploy a node.js package via a jenkins job

I'm looking to set up a Jenkins job that will publish a package to npmjs.com. The source code for the package is located in a GitHub repository. While I am able to successfully publish the package from my personal computer by running 'npm publis ...

I want to set a single background image for all slides in fullPage.js. How can I achieve this

I am attempting to replicate a similar effect as shown in this example: The demonstration above utilizes the fullPage.js plugin. You may have noticed how the background image remains consistent while navigating through different sections. I have searched ...

Is it advisable to use Angular $resource JSON Callback if it's not functioning correctly?

I am in the process of creating a resource to send data to my controller for an existing API that I need to connect with. Unfortunately, I do not have the ability to make any changes on the backend. Current state of my Resource factory: 'use strict& ...

The HTML Bootstrap collapse feature is not functioning correctly upon the initial button press

Could you assist me with implementing a bootstrap and javascript collapse feature? I have two collapsible cards. The first card should be visible initially, but then switch to the second card when clicked on a link. However, upon the first click, both card ...

Search a database for a specific set of ObjectID using Mongoose

I'm currently developing an API using node.js, express, and mongoose. As I am still new to mongosse, I have been exploring different approaches to achieve what I need. In my database, I have two collections: users and expenses. Here's an exampl ...

What is the best way to develop a widget that loads asynchronously by implementing AJAX, JavaScript, and PHP?

Currently, this widget is in need of items that are sourced from a php file. For instance, the javascript function should generate a table within this div element. <div id="widget"></> The aim is to dynamically update the content with the ht ...

Difficulty in accessing controller data in AngularJS with ng-repeat

I am trying to display comments using ng-repeat in a section, but I am having trouble accessing the data. Even after debugging, I cannot access the data without modifying the controller. I am new to Angular and prone to making mistakes. HTML / JS &apo ...

What is the best method for storing a model in a database?

Hello, I am currently attempting to save a model to the database. I am simply inputting the value of a title in order to save it, as my id is set to auto increment. However, I have encountered an issue where my attempts have been unsuccessful. Can someone ...

Experiencing difficulties with executing numerous NodeJs queries

Could someone assist with rendering multiple queries in a Nodejs view? The console shows Promise {pending} and I can't figure out what's causing the issue. I'd appreciate any help or guidance on how to fix this problem. router.get('/ ...

Throw an error if the entry is not found in the Firebase database

I have an array containing various objects. Users should be able to access all objects using moduls/, and a specific one with moduls/$id. However, if the requested modul does not exist, the database should return an error to inform the client that there is ...

The "maxfilesexceeded" event in dropzone.js does not seem to be triggered when adding files programmatically

In my Vue.js project, I am using dropzone with the maxFiles: 1 option set. To display an existing file from the server in dropzone, I have added the following code: let mockFile = { name: 'Filename', size: file.size }; myDropzone.emit('added ...