Convert XML to an HTML table in real-time as new elements are introduced

Currently, I have JSON and AJAX code that fetches XML data every second, which is working smoothly. When I added an XML element, it automatically gets added to an HTML table. The issue arises when I call the function every 3 seconds; the page refreshes due to new elements being added to the table, causing an annoying viewing experience with the page refreshing constantly. To combat this, I want the code to trigger only once when a new element is added and update the table accordingly. This is for a customer info screen in a self-service cafe program, where any newly added items by the seller should reflect on the customer monitor.

<script>

        $(document).ready(function() {
            setInterval(function() {
                $('#tableBody').empty();
                // ajax call to load XML and parse it
                $.ajax({
                    type: 'GET',
                    url: '01.xml',
                    dataType: 'xml',
                    success: function(xml) {

                        $(xml).find('dsname').each(function() {


                            $('#tableBody').append(
                                '<tr>' +
                                    '<td>' +
                                        $(this).find('STOKADI').text() + '</td> ' +
                                    '<td>' +
                                        $(this).find('BORC').text() +'₺'+ '</td> ' +

                                '</tr>');
                        });
                    }
                });
            }, 3000);
        });

        
    </script>

My XML data when sellers try to sell something:

My XML data when the sell menu is empty:

I wish to implement a function that checks for newly added elements in the XML file and then triggers the necessary action.

Edit my page for nick:

<html>
        <head>
            <meta charset="UTF-8">
            <title>Customer Screen</title>
            <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
            <link href="plugins/datatables/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
            <link href="dist/css/pageDesign.min.css" rel="stylesheet" type="text/css" />
            <script src="plugins/jQuery/jQuery-2.1.4.min.js" type="text/javascript"></script>
        </head>
        <body>
            <table class='table table-bordered table-striped datatable'>
              <thead style='background:#999900;'>
                <tr>
                  <th>SIRA</th>
                  <th>ÜRÜN</th>
                  <th>FİYAT</th>
                </tr>
              </thead>
              <tbody id="tableBody">
                  
              </tbody>
            
            </table>
            <img src="1.png" style="width: 250px; height: 250px; margin-left: 800px">
        </body>
    </html>

Answer №1

To simplify the process, you can assign classes to the cells in the stokadi and borc tables. Then, before adding each value from the XML, check if it already exists in the table.

const validateUpdate = (xml) => {
  const xmlValues = $(xml).find('dsname stokadi').map(function() {
    return $(this).text()
  }).get();
  
  const tableValues = $('#tableBody .stokadi').map(function() {
    return $(this).text()
  }).get();

  return xmlValues.length != tableValues.length || !xmlValues.every((v, i) => v === tableValues[i]);
}

const applyUpdate = (xml) => {
  if (validateUpdate(xml)) {
    $('#tableBody').empty();
    
    $(xml).find('dsname').each(function() {
      const stokadi = $(this).find('STOKADI').text();
      const borc = $(this).find('BORC').text();
      
      $('#tableBody').append(
        `<tr><td class="stokadi">${stokadi}</td><td class="borc">${borc}₺</td></tr>`
      );
    });
  }
}

let xmlData = `<root>
...
</NewDataSet>`;

applyUpdate(xmlData);

// Below is just a snippet of code that would be used when loading new XML data after intervals
/*
xml2 = `<root>
...
</root>`

setTimeout(() => {
  applyUpdate(xml2);
}, 2000);
*/

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>STOKADI</th>
      <th>BORC</th>
    </tr>
  </tbody id="tableBody">
  </tbody>
</table>

The functions validateUpdate and applyUpdate should be defined outside the $(document).ready block like:

$(document).ready(function() {
  setInterval(() => {
    $.ajax({
      type: 'GET',
      url: '01.xml',          
      dataType: 'xml',    
      success: function(xml) {
        applyUpdate(xml)
      }
    });
  }, 3000);
});

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

Personalize your message in a JavaScript alert using Bootstrap notifications

On numerous websites, a new visitor landing on the page is greeted with an alert notification that pops up in either the bottom right or left corner. The code below functions perfectly fine, except for my unsuccessful attempts to change the message text w ...

CodeIgniter encountering a dilemma with session logout functionality

if ($this->Adminmodel->check_credentials($this->input->post('email'), $this->input->post('password')) =="true") { redirect("admin/dashboard"); } ...

What is the best method to redirect users who are not logged in from every URL when using PassportJs?

I am currently developing a web application using NodeJS, and I have integrated PassportJS with passport-local-mongoose for authentication. Below is the code snippet I've created for the root route to verify if the user is logged in: app.get('/ ...

Tips for utilizing JavaScript to upload a file in Webform and make it accessible in the global PHP variable $_FILES

I'm feeling a little overwhelmed and frustrated. I've come across a bunch of solutions, but none of them seem to work fully or correctly!? My task is to create an HTML form that allows users to upload one or more files to the web server using AJ ...

Is it possible to connect a date range picker custom directive in AngularJS with the behavior of AngularUI-Select2?

I'm currently utilizing Angular UI - Select2 directive for displaying an option box. Bootstrap Date-Range Picker for showing a date picker Both functionalities work effectively on their own. Functionality of the Date picker Whenever there is a ch ...

Combining multiple data sources into a single input field in VueJs

I've been exploring the idea of incorporating multiple values into a vue form input binding Here's an example snippet of my code. <template> <div> <label for=""> Employee </label> <input class="form-contro ...

Interfacing Contact Form Data from Vue Application to Magento Using API - A Step-by-Step Guide

Introduction A custom vue-component has been implemented on the application, serving as a contact form. This component is imported into the header component and enclosed within a modal container. The primary function of this contact form is to trigger an ...

A guide on navigating through JSON data in PHP

I've been researching this subject extensively, but I'm struggling to interpret this JSON string in PHP. I need to extract "summary, description, start, end" for each event. { "pages": { "current": 1, "total": 1 }, "events": [ ...

Create a feature in three.js that allows users to click on an object to display information about the

After loading an object using the GLTF loader into my scene, I want to create a point on this object to display popup info. Is there a way to add a point to a specific location on the object? ...

Is there a way to enforce mandatory fields on material-table?

During my current project, I am utilizing a material-table interface to perform CRUD operations. I am interested in finding out if there is a way to make certain fields required when necessary. Despite my research efforts yielding minimal results, I have ...

Failure to update content with new text in Ajax when GET/POST variables are included

I've been following a tutorial on Ajax functionality, and I have set up my code exactly like mmtuts. However, the new value isn't displaying until I make an adjustment to my test.js file: The original code that is not functioning as expected: $ ...

Ensure that each of the two divs maintains a 16:9 aspect ratio, and utilize one div to fill any remaining empty space through the

This layout is what I am aiming for: https://i.sstatic.net/uZdty.png While I can achieve a fixed aspect ratio with a 16:9 image by setting the img width to 100%, I run into an issue where the height scaling of flexbox becomes non-responsive. The height re ...

What is the best way to manage uncaught errors within the simple-peer library?

Currently integrating feross' simple-peer library and encountering an occasional error: Uncaught Error: Ice connection failed. at r._onIceStateChange at RTCPeerConnection.t._pc.oniceconnectionstatechange This error is directly from the library and ...

Retrieving information from the controller within the error callback of a jQuery AJAX request in ASP.NET MVC

I've been working with a jQuery ajax script that looks like this: $.ajax({ type: "POST", url: "Main/receive", // the method we are calling contentType: "application/json; charset=utf-8", data: JSON. ...

What is the best way to iterate through indexed numbers within a stdClass Object?

The desired output that I am attempting to access is as follows: stdClass Object ( [results] => stdClass Object ( [columns] => stdClass Object ( [name] => Name [id] => ...

How can I customize the styling of an SVG pseudo element using Font Awesome 5?

I've implemented font awesome 5 pseudo elements to attach an :after tag to my element as shown below: &:after { content: "\f068"; font-weight:400; color:$brandRed; float:right; font-family: "Font Awesome 5 Pro"; } The c ...

Updating and eliminating text within an array of objects using Vue JS

My Axios request pulls in an array of objects named 'uniquecolors'. Here is what it looks like: mycolors color: [GREEN, RED, BLUE, YELLOW, ORANGE,ORANGE,GREEN,] color: [GREEN, RED, BLUE, YELLOW, ORANGE,ORANGE,GREEN,] color ...

Implement a click event using jQuery specifically for Internet Explorer version 7

How can I add an onclick attribute using jQuery that is compatible with IE7? So far, the following code works in browsers other than IE8 and Mozilla: idLink = Removelst(); var newClick = new Function(idLink); $(test1).attr('onclick', null).clic ...

Expanding your JavaScript skills: Tackling nested object key and value replacements

I am looking to manipulate the values of a nested object using JavaScript. The structure of the object is outlined below. let jsonObj = { "service":[ { "name":"restservice", "device&quo ...

Service Worker error - Received redirected response when RedirectMode is not set to "follow"

Browser: Firefox 58.0.2 (64-bit) I am attempting to create a very basic service worker to store content for offline viewing, following the guidelines provided here and here. After installing the service worker successfully upon loading the page for the f ...