Feeling uncertain about how to utilize AJAX using the XMLHttpRequest object

The JavaScript function is:

function loadData()
{
  const xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function()
  {
    if (xhttp.readyState == 4 && xhttp.status == 200)
    {
      const data = xhttp.responseXML.documentElement.getElementsByTagName("ELEMENT");
      const text = data + data.length;
      document.getElementById("content").innerHTML = text;
    }
  }
xhttp.open("GET", "ajax/data.xml", true);
xhttp.send();
}

The response (viewed in the browser console) shows:

<?xml version="1.0" encoding="UTF-8"?>
<ELEMENT>
  <ID>0</ID>
</ELEMENT>

I expected the output to be something like "[0], 1" (indicating a list with one element and its length), but it actually prints "[object NodeList] 0", indicating that it doesn't recognize any "ELEMENT" elements. What could be causing this issue? Thank you.

Answer №1

x represents a group of XML nodes.

var textValue = x.item(0).nodeValue + ', ' + x.item(0).childNodes.length;

Latest Update

var response = xmlhttp.responseXML.documentElement;
var IDs = response.getElementsByTagName('ID');
var content = response.nodeName + ', ' +  response.nodeValue + ', ' + IDs.length;

The childNodes attribute retrieves 3 elements, including two empty text nodes (before and after <ID>2</ID>).

var childNodesList = response.childNodes;
for (i=0; i<childNodesList.length; ++i) {
    print("'" + childNodesList.item(i).textContent +  "'");
}

This code snippet will display:

''
'0'
''

Answer №2

The variable named "x" will actually be a NodeList, not a string. You'll need to figure out what that "txt" string should contain by looping through your <call> elements or whatever method suits your needs.

Additionally, remember to include the var keyword in all your variable declarations. If you don't, a tiny kitten somewhere might end up with a thorn in its paw.

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

Stop a user from adding duplicate tasks

I have developed a JavaScript code for creating a todo list. Currently, I am working on the phase of adding tasks to the list. The user wants to ensure that if a task is entered once, it cannot be entered again. const taskInput = document.getElementById(&a ...

Unable to locate module using absolute import in a Next.js + TypeScript + Jest setup

Currently in my NextJS project, I am utilizing absolute imports and testing a component with Context Provider. The setup follows the instructions provided in this jest setup guide TEST: import { render, screen } from 'test-util'; import { Sideb ...

Refresh the dropdown menu selection to the default option

My HTML dropdown menu includes a default option along with dynamically generated options using ng-options. The variable dropdown is bound to the dynamic options, not the default one. <td> <select ng-model="dropdown" ng-options="item as item.n ...

Refresh the nested state without affecting the parent state using a URL parameter in ui-router

Within my app.js file, I am experiencing an issue with a parent state and a nested state. The parent state contains a button that is responsible for controlling what is displayed in the nested state. This is achieved by setting a url parameter, and the con ...

Modifying the input placeholder color with ng-style

I am working on setting the color of my input placeholder using a dynamic color defined in a $scope variable in my controller for my HTML code. The $scope variable is structured as follows: $scope.primaryColor={"color":colorVar}; //colorVar represents th ...

Utilizing a for loop to iterate through the results of child_process.spawnSync when executing a

First, I will share the code snippet below: Let me illustrate the issue I am encountering: for (var i = 0; i < arrayleng.length; i++) { var oneScript = spawnSync('python', ["/home/demo/mypython.py", arrayleng[i].path]); // console.lo ...

How to prevent VueJS observer from monitoring a temporary variable

My VueJS and Observer objects are causing me trouble. I am encountering an issue where I assign a part of my object to a temporary variable for later use, update the original part with new data, and then revert it back to its original state after 8 seconds ...

Shifting annotations on a Bar Graph featuring Negative Values on Google's Chart Maker

Incorporating google charts into my MVC project. Looking to create a bar chart that accommodates negative values. Desire annotations on the same side as the end of the bar for negative values (similar to positive values shown in the green box below). ht ...

Having trouble implementing CORS in a Slim API

I'm facing challenges in setting up CORS with Slim and AngularJS. AngularJS HTTP Request: $http({ method: 'GET', headers: { 'Content-Type': 'application/json', Accepts: 'application/json&ap ...

I encountered an issue while attempting to include Access-Control-Allow-Origin in my WCF library Project

Can someone help me figure out why this ajax call isn't working as expected? $.ajax({ type: 'GET', url: "http://localhost:8732/Design_Time_Addresses/InMotionGIT_NT.Address.Service/AddressService/json/capitalize", da ...

Dimensions of Collada Element

This is my first time delving into the world of javascript, WebGL, and Three.js. I successfully added a dae 3D model to my scene, but now I need to determine its size in order to generate objects within it. However, upon adding the dae object, it appeared ...

Creating a function within an ajax call presents a challenge that needs to be

Below is an example of my ajax function: for (var i = 0; i < 50; i++) (function(i) { jQuery('#skin_'+i).click( function() { var result = $('#idskin_'+i).val(); $.ajax({ url: 'aja ...

Retrieve numerous tables as individual entities in a single query

In the process of creating an interface where the selection in the first dropdown influences the available options in six subsequent dropdowns. For each dropdown, the values and display names are retrieved from a table as shown below: $arr = arra ...

Adjusting window size when page is resized

While browsing through SO, I stumbled upon this interesting piece of code: var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w. ...

Change the URL structure from ex.com/forum?id=1 to ex.com/#/forum?id=1 in AngularJS

Hey there! I'm in the process of creating a Forum using AngularJS and need some guidance. First things first! I've successfully established a connection to my database with: <?php session_start(); $db = new mysqli("localhost","root",""," ...

Utilize AngularJs and JavaScript to upload information to a JSON file

Exploring the realm of Angular JS, I am on a quest to create a CRUD form using AngularJs and Json with pure javascript without involving any other server side language. The script seems to be functioning well but is facing an obstacle when it comes to writ ...

How to resolve undefined Axios Authorization headers in Vue.JS and Node.JS interactions?

Encountering an issue while trying to set authorization headers for my axios instance. Here is the code snippet from my Vue.JS application running on http://localhost:8080 : axios.defaults.headers.common['Authorization'] = 'Bearer ' ...

Retrieve the value from a variable located outside an API function call

As I work on developing a chat application project that includes abusive text detection, I have encountered an issue with accessing data from the Perspective API. While I am able to set attributes within the API function, I face challenges accessing them o ...

The JavaScript object is unable to reach the PHP controller

When I attempt to send a JavaScript Object to my PHP controller, it is arriving empty. Here is the object: https://i.sstatic.net/19gFV.png Upon arrival, the object appears empty. Here is my AJAX code: https://i.sstatic.net/ekHsC.png var SendMovs = { ...

Upon logging in to the first HTML page, the user will be automatically redirected to the second HTML page while passing values

Is there a way to automatically redirect users to Login2.html when selecting "TEAM" in the dropdown on Login1.html, using the values entered in Login1.html? Similarly, can we redirect them to the Premium page when they select "Premium"? I need a solution u ...