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

JavaScript XML Serialization: Transforming Data into Strings

When trying to consume XML in an Express server using express-xml-bodyparser, the resulting object is not very useful. This is the XML: <SubClass code="A07.0"/> <SubClass code="A07.1"/> <SubClass code="A07.2"/> <SubClass code="A07.3" ...

Checking for the accuracy of the provided full name

There is a specific task at hand: The field labeled “First Name Last Name” must only contain 2 words, with each word being between 3 and 30 characters in length. Additionally, there should be only one space between the first and last name. The issue t ...

Confirm that the form is valid when a specific requirement is fulfilled

I am currently working on a credit card project that involves using a JavaScript function called validateCreditCard to validate credit cards and determine the type. The idea is to store the credit card type as the value of a hidden input field called cardT ...

The carousel comes to a halt once it reaches the final slide and does not continue cycling

Currently working on a website project for a client and utilizing Bootstrap to create a carousel feature. I am specifically using Bootstrap 3.0. After searching for a similar issue here, I found two cases that resemble mine but unfortunately have no soluti ...

Verify whether an image is present without actually displaying it

I am currently integrating a script for hover-functionality: function VerifyImage(url) { var httpRequest = new XMLHttpRequest(); httpRequest.open('HEAD', url, false); httpRequest.send(); return httpRequest.status != 404; } The c ...

Making a request to the Model-View-Controller (M

Can cross-domain ajax be achieved in MVC architecture? Currently, I am using jsonp and it works flawlessly when both sites are on localhost. However, I am unsure if the mvc architecture blocks the jsonp call. <script src="www.example.com"></scrip ...

Looking to remove a specific field from a URL with jQuery

I am trying to extract a specific tag from a string, like in this example: url = 'https://example.com/tag33?tag=17&user=user123'; The goal is to retrieve the value of the tag. If anyone has a solution or suggestion on how to achieve this, ...

Using a JSON file as a variable in JavaScript

Hello there everyone! I am looking to create a multilingual landing page. The idea is to have a language selection dropdown, and when a language is chosen, JavaScript will replace the text with the corresponding translation from a JSON file. However, I a ...

What is the proper method for implementing an event listener exclusively for a left mouse click?

Is there a way to make Phaser recognize only left mouse clicks as click events, excluding right and middle clicks? Check out this Phaser example at the following link: https://phaser.io/examples/v2/basics/02-click-on-an-image. ...

Internet Explorer struggling to function due to JavaScript errors

While Chrome and Firefox breeze through the page, it seems to hang for an eternity in Internet Explorer. Here is the problematic page: ============= Error Details: User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2 ...

The map displayed on google.com appears different from the one featured on our website

The integration of the JS for the Google map on our website is working smoothly without any issues. However, when I zoom into our address on google.com/maps, our Hotel is listed as "Hotel". On the map displayed on our website, there are only a few entries ...

Error: An unexpected identifier was found within the public players code, causing a SyntaxError

As a newcomer to jasmine and test cases, I am endeavoring to create test cases for my JavaScript code in fiddle. However, I'm encountering an error: Uncaught SyntaxError: Unexpected identifier Could you guide me on how to rectify this issue? Below is ...

What is the process for configuring simultaneous services on CircleCI for testing purposes?

My current project involves running tests with Jasmine and WebdriverIO, which I want to automate using CircleCI. As someone new to testing, I'm a bit unsure of the process. Here's what I've gathered so far: To run the tests, I use npm tes ...

Is there a way to obtain an array after subscribing to an RxJS method?

I am struggling with the following code snippet: Rx.Observable.from([1,2,3,4,5,6]) .subscribe(x=>console.log(x)); Is there a way to modify this code so that instead of iterating through the array elements from the .from() method, I can return the enti ...

Tips for accessing id from $http.get in angular.js

Hello everyone, I'm new to Angular.js and currently learning it. I need help in retrieving data from the following API URL: . I am unsure how to implement this in my controller.js file. Below is the code I have so far, can someone please guide me on h ...

There are currently no articles found that match the search query

Recently, I started working with Django, but I am facing an issue with slug. Whenever I send a request to the Slug, I encounter an error. The error message I receive is: Articles matching query does not exist. Furthermore, I am facing another error while ...

Replicate the action of clicking on the download button in R

Is there a way to programmatically simulate clicking on the download button on the following website using R and download the TSV table? I have looked into methods such as Rselenium and PhantomJS, but they seem to be outdated now. I came across V8 as a po ...

Disappear notification with jQuery after a set amount of time

I stumbled upon this amazing script for displaying warning messages from this source: Within the script, it is configured to hide the warning message following a click event. $('.message').click(function(){ $(th ...

Tips for inserting an element into every tier of a multi-layered array

I am faced with a challenging task of assigning an id field to objects within an array that has infinite levels. The rule is simple - for every level, the ID should correspond to the level number starting from 1. { "name": "Anything2&quo ...

Navigating a collection of objects in JavaScript: A step-by-step guide

My data consists of objects in an array with the following structure: [{\"user\":\"mcnewsmcfc\",\"num\":11},{\"user\":\"ManCityFNH\",\"num\":7}]; To clean up the array, I'm using this code: ...