Unexpected Alert Triggered by XML Parsing Error

 <script>
      async function loadData() {
        var data = await fetch("Product.xml");
        var parsedData = await data.text();

        var parser = new DOMParser();
        var Product_document = parser.parseFromString(parsedData,"text/xml");
        var results = "";
        var AlertBox = ""
        var user_id_input = document.getElementById("user_id").value;
        var todos = Product_document.getElementsByTagName("product");
        for(var i = 0; i < todos.length; i++) {
          var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
          var Code = todos[i].getElementsByTagName("Code")[0].childNodes[0].nodeValue;
          var Quantity = todos[i].getElementsByTagName("Quantity")[0].childNodes[0].nodeValue;
          var Description = todos[i].getElementsByTagName("Description")[0].childNodes[0].nodeValue;
          var Price = todos[i].getElementsByTagName("Price")[0].childNodes[0].nodeValue;
          if(user_id_input === Code) {
            results = "<div>"
            + "Code: " + Code 
            + ",<br/> Name: " + Name 
            + ", <br/>Quantity: " +  Quantity 
            + ",<br/> Description  " +  Description 
            + ",<br/> Price " +  Price
            + "</div><br/>";
            AlertBox= "True";
          }
         if(AlertBox !== "True") {
             alert("Error");
         }
        }
        document.getElementById("results").innerHTML = results;
      }
    </script>
  

I'm in the process of developing a web application that takes input from users, parses an XML file, and then displays relevant information. This functionality is already working smoothly on my end.

In doing so, I encountered an issue where I wanted to implement an error alert when the user's input doesn't match any of the elements in the XML file. However, each time the app checks against an element that doesn't match the user input, I receive multiple error alerts unexpectedly. I am currently at a loss as to how to rectify this situation. see image description here

To troubleshoot, I attempted using a variable that would change to 'true' upon a valid match with the input, allowing only one error alert to show up if the variable remains 'false.' Unfortunately, even after implementing this approach, I still encounter the same issue with the error alert persisting. see image description here

Answer №1

After reviewing your code, it seems that the issue is with the nodeValue property which is returning null.

When you call nodeValue on an element tag (nodeType 1), it returns null. It only returns the actual text content when called from a text element (nodeType 3). Since the 'Code' tag is of type element and has a child of type text, you are not getting the desired text value. More information on nodeType can be found here.

To retrieve the correct result from nodeValue, you should use the following syntax:

var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].firstChild.nodeValue;
.

If you want to get the text content from an element, you can also use this alternative code:

var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].textContent;

The if condition will now execute correctly as long as the user_id_input variable has the correct value. If the function loadData is triggered before the user inputs values into the form fields, make sure to execute the function upon form submission to ensure all required fields have been filled. For more information on HTML Forms and managing them with JavaScript, refer to this guide.

I recommend using let and const instead of var. Furthermore, if you intend to use your variable AlertBox as a boolean, consider utilizing the boolean datatype in JavaScript by writing it like this:

let AlertBox = false; or let AlertBox = true;

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

Leveraging external Javascript files in Ionic framework version 3 and above

Hey there, I'm currently working on integrating the Mapwize SDK, an external Javascript library, with the latest version of Ionic. I've encountered the common challenge of getting Javascript to function smoothly with Typescript. Although I'm ...

Depending on external software packages

Can you explain the potential risks associated with using third-party packages and npm in a broader sense? If I were to install a third-party package like semantic-ui-react using npm, is there a possibility that I may not be able to use it on my website i ...

The function .get() is expecting callback functions, however it received an undefined object at route.(anonymous function) as get[]

Hey everyone, I've encountered an error in my server.js file and being a beginner I'm struggling to find a solution. I've searched through numerous answers on Stack Overflow but haven't been able to resolve it. Can someone please help m ...

Encountering the error message "Undefined variable '$'" in a script that is loaded after jQuery

My code is simple - it loads jQuery first, followed by a script that uses the $ syntax. However, I keep encountering the error: ReferenceError: $ is not defined Initially, I suspected that the async attribute on the script tag was the issue, but changi ...

Making an Ajax request that returns JSON data, which then needs to be appended into a select box

Struggling with including Json data in a select box has been an issue for me. Despite successfully retrieving the json data within my Ajax call, the problem persists. The ID appears in the select box as an option along with the name, which is not what I de ...

Generating a CSS rule based on a query string

Receive query string var queryString = window.location.search; Eliminate ? from the start of the query string queryString = queryString.substring(1); Query string handler var parseQueryString = function( queryString ) { var params = {}, queries, t ...

Having trouble with JQuery's $.post function not functioning on your web server?

I'm encountering an issue with my script that uses Ajax to send a request to my PHP file for updating a txt file. Interestingly, the script works perfectly fine on my localhost but fails to work on the webserver. Testing HTML code: <!DOCTYPE html ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

Deactivate the button for each package based on a specific PHP value

Are you looking to purchase a package or multiple packages? The available packages are displayed in the table below. I would like to implement a feature where once a user buys a package, the corresponding button for that package is disabled. Here is my cu ...

Tips for adjusting the font size on Firefox Browser

My website is functioning perfectly in all browsers except for Firefox. The text in Firefox appears larger than it should and gets pushed out of its designated div. How do I adjust the text size specifically for Firefox? I attempted using the following co ...

What is the process for building a series of HTML elements using jQuery?

Is it possible to create a moving conveyor belt of html elements (such as divs) using jQuery, and if so, how can this be done? For example: (as shown above, rectangles move from left to right; new ones are added and the last one is removed) And then: [ ...

Troubleshooting issue: Incompatibility between NODE.JS Passport and mongoose

Currently, I am diving into the world of Node.js and exploring all its features with the help of Scotch's tutorial (https://scotch.io/tutorials/easy-node-authentication-setup-and-local). Following the tutorial, I implemented what was suggested, which ...

What is the best way to incorporate a progress bar animation into my notification?

Seeking assistance to implement an animated progress bar that changes colors gradually over time based on a variable [timer]. Can anyone lend a hand with this? Thank you! https://i.sstatic.net/lhgeF.png $(document).ready(function(){ window.addEvent ...

the getAsObject method of the converter was not called

I am currently dealing with an issue related to my <h:selectOneMenu>. <h:selectOneMenu id="LoanType" style="width: 180px; font-size: 12px;" value ="#{editLoan.currentLoanType}" converter="#{convertToLoanType}"> <f:selectItems value="#{e ...

Increment operator `++` in Javascript has two forms: `i

There is a common practice in JavaScript where i++ is used to increment the value of a variable by one. This is commonly seen in loops like the following: for (var i=1; i<=10; i++) { console.log(i); } However, what happens when we use ++i; instead ...

Array reducer producing unexpected result of NAN

Query I am facing an issue with a specific array and reducer function. The array in question is as follows: let oddsArray = [undefined, undefined, 5, 5] Accompanied by this reducer function: const reducer = (accumulator, currentValue) => accumulator ...

What methods can be used to continuously send data to another web page within my website using XMLHttpRequest()?

As I delve into working with node.js and express.js, my primary goal is to efficiently tackle a specific issue. One of the pages on my website is tasked with receiving location data in latitude var lat and longitude var long. The challenge at hand is to c ...

Performance issues are being experienced on website for tablet and smartphone usage due to slow loading times

My client's website is running on an old Dell PowerEdge 2600 with Windows Server 2008. While desktop and laptop access to the site is smooth, access from tablets and smartphones is extremely slow, taking over 10 minutes to load or sometimes not loadin ...

Integration of AngularJS and Node.js using ExpressJS

Currently, I am working on developing an app using Node.js with Express and AngularJS. I have a query regarding whether it is feasible to delegate all landing requests to AngularJS while solely utilizing Node.js for APIs. This implies that all routes defi ...

Incorrect tabindex order is applied after selecting a hidden element

Experience JSBin here Access Standalone Version In the scenario where I have 3 input fields with tabindex set to 1, 2, and 3: When I click on the first (Search) box and then tab, everything works as expected. However, if I happen to select one of the ov ...