The XML response from Ajax is returning as empty

My goal is to retrieve XML data from an ajax request and extract information using the DOM. The ajax request itself seems to be working fine as I can access AjaxRequest.responseText without any issues. However, I am encountering an error message stating:

'null' is not an object (evaluating 'resturantsCategoriesAjaxXML.getElementsByTagName')

Additionally, when attempting to log the responseXML, all I see is null as if it hasn't been defined. Below is the complete JS code handling the AJAX request (apologies for the unconventional variable names) along with the simple XML being fetched. Thank you for your assistance :D

Javascript:

restaurantsCategoriesAjaxRequestAddress = "testFiles/categoriesAjax.xml";
restaurantsCategoriesAjaxRequest = new XMLHttpRequest();
restaurantsCategoriesAjaxRequest.onreadystatechange = function(){
if(restaurantsCategoriesAjaxRequest.readyState == 4){
    restaurantsCategoriesAjaxXML = restaurantsCategoriesAjaxRequest.responseXML;
    console.log(restaurantsCategoriesAjaxRequest.responseXML);
    categoriesArray = restaurantsCategoriesAjaxXML.getElementsByTagName("category");
    categoriesArrayLength = categoriesArray.length;
    alert(categoriesArrayLength);
    categoriesArrayIterationControl = 0;
    while (categoriesArrayLength >= categoriesArrayIterationControl) {
        categoryName = categoriesArray[categoriesArrayIterationControl].getAttribute("name");
        //create new <li> object
        //add to categories menu on restaurants page
        alert(categoryName);
    }
}
}
restaurantsCategoriesAjaxRequest.open("GET", restaurantsCategoriesAjaxRequestAddress, true);
restaurantsCategoriesAjaxRequest.overrideMimeType("text/xml");
restaurantsCategoriesAjaxRequest.send();
console.log(restaurantsCategoriesAjaxRequest.readyState);

XML:

<?xml version='1.0'?>
<category name="Fast_Food" id="1120"></category>
<category name="Chinese" id="1108"></category>
<category name="Italian" id="1230"></category>

Answer №1

I believe that your document does not adhere to proper XML formatting. It appears that you need to include a parent tag above the "<category>"

Answer №2

Make sure to include a root element that wraps around all your other elements.

Consider using <sections> with opening tag </sections> to encompass your various <section> components.

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

Obtaining the value of cookies in express js is a simple task that

Is there a way to retrieve the value of a cookie? const cookieParser = require('cookie-parser'); app.use(cookieParser()); app.get('/', (req, res) => { res.setHeader('Set-Cookie', 'Cookie=HELLO'); }); I' ...

Error encountered when WebDriverIO attempted to connect to Appium due to a lack of compatible capabilities

I'm currently facing an issue while attempting to link my virtual Android Device through Appium with my Webdriverio script for the purpose of automating some testing tasks. Here are the capabilities that I have set: capabilities: [{ // N ...

Obtain the total number of result entries

I'm working on a project involving JS and PHP. My goal is to call a PHP file using Ajax and have it return the count of result lines. I use echo for this: $connection = new PDO($source, $user); $query = "SELECT * FROM scores WHERE username = '" ...

Using JavaScript to dynamically set a background image without the need for manual hard-coding

My attempt was to showcase images as a background image upon mouseover event for the div section with id 'message' by manually coding JavaScript functions for each image like this: Here is the HTML code inside the body section <div id = "mes ...

Incorporating images with JavaScript in Jade templates

Currently I have a layout.jade code that I am looking to modify the javascript for. My goal is to load an image onto the page every time it is reloaded using jade. Here is the existing code: html head title= title script(src='/libs/jquery/j ...

The error in React syntax doesn't appear to be visible in CodePen

Currently, I am diving into the React Tutorial for creating a tic-tac-toe game. If you'd like to take a look at my code on Codepen, feel free to click here. Upon reviewing my code, I noticed a bug at line 21 where there is a missing comma after ' ...

Organize an array of JSON objects based on a specific key and eliminate any duplicated entries

I am grappling with the challenge of grouping an array of JSON objects by the id_commande attribute and eliminating any duplicates. I am finding it quite perplexing to figure out a solution to this issue without relying on a library like lodash. Ideally, I ...

How to Send a JSON-formatted object to the Django backend?

When working with JavaScript, I am attempting to convert an Object into JSON and then send it to the back-end in Django. First step involves creating a list of lists: function get_account_info(){ var account_list = []; $('.card').each(f ...

Ways to adjust the height of one panel based on the height of surrounding panels

I have a layout with three panels: two on the left side and one on the right. <div class="row"> <div class="col s6"> <div class="panel"> content1 </div> <div class="panel"> ...

Re-sequence a contiguous array by mapping and filtering its elements

Within my React code, I have a list component that utilizes array.map to display a list of items. The list items have alternating backgrounds; every other item's background color is determined by whether the id field from the data structure is even o ...

Is it possible to use just one <map> tag for multiple images in jQuery or JavaScript?

I have multiple images on my website <img usemap="#slideMap_branches" src="branches.png" width="890" height="270" alt="Slide 4"> <img usemap="#slideMap_order" src="order.png" width="890" height="270" alt="Slide 2"> <img usemap="#slideMap_c ...

Upon the initial loading of the React component, I am retrieving undefined values that are being passed from the reducer

Upon the initial loading of the React component, I am encountering an issue where the values originating from the reducer are showing up as undefined. Below is a snippet of my code: const [componentState, dispatchComponentState] = useReducer( versionReduc ...

Creating a new route in a Express JS server to specifically handle POST requests

Just starting to learn the ropes of Javascript, and I'm diving into express to create an application that will enable users to craft new recipes, explore existing ones, and view details about each recipe. To get things moving, I've launched my s ...

Uploading files through AJAX modal window (elevate)

Is there a way to successfully upload files within an AJAX modal window in Lift? I attempted the following approach: ajaxForm( bind("upload", template, "file" -> SHtml.fileUpload(processFile _), "submit" -> SHtml.ajaxSubmit("Subm ...

Link up each query with every php echo

Suppose I have the following PHP code: $logger = $_SESSION['logger']; $postquery = $con->query("SELECT * FROM posts ORDER BY id DESC LIMIT 5"); while($row = $postquery->fetch_object()){ $posts[] = $row; } And then, this section of ...

Linking Java objects with Node.js variables

In this snippet of code, I am utilizing the 'java' module in node.js to create Java objects. Specifically, I am creating four Java objects and aiming to consolidate them as a single object by using the variable 'args' to store these Jav ...

Magnific Popup displaying only the initial item

As someone new to using jQuery and Magnific Popup, I am working on a grid of images. When an image is clicked, I want Magnific Popup to display a specific div containing information relevant to that particular image. <div class="grid"> <div c ...

Integrate geographic data in GeoJSON format into a Leaflet map by using the Django template

In my Django view, I am fetching results of an SQL query and rendering it on the index.html page of my web map. The POST request successfully returns the acreage calculated from the SQL query to the page. I am also attempting to display the geojson data fr ...

What is the method for retrieving array values from an attribute?

I am currently developing an Angular 6 application and I need to pass and retrieve array values dynamically through attributes. Here is the code snippet I have used for this purpose: HTML: <ul class="list-unstyled" id="list" [attr.parent_id]="123"> ...

Error encountered with the $get method of AngularJS Provider during configuration() function

Recently, I configured a Provider that fetches a language JSON file from a web server and delivers it to Angular within the config() method. Here is the provider setup: .provider('language', function () { var languageWsURL , languageC ...