Arranging information extracted from an XML document following an ajax request

Here is a snippet of XML data sample to work with:

<?xml version="1.0" encoding="ISO-8859-1"?>
<CATALOG>
    <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
    <CD>
        <TITLE>Greatest Hits</TITLE>
        <ARTIST>Dolly Parton</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>RCA</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1982</YEAR>
    </CD>
</CATALOG>

I need to arrange this data in ascending order based on the year, after an ajax call.

function handleResponse () {
    "use strict";
    var ajax = new XMLHttpRequest();;

    if ( ajax ) {
        ajax.onreadystatechange = function () {

            if ( ajax.readyState == 4 ) {

                if ( ajax.status == 200 || ajax.status == 304 ) {

                    // console.log( ajax.responseXML );

                    var returnedData = handleXML( ajax.responseXML );

                    var collection = document.getElementById( "collection" );

                    collection.innerHTML = returnedData;

                }

            }

        };

        ajax.open("GET", "catalog.xml", true);
        ajax.send(null);
    }

}

function handleXML ( response ) {
    "use strict";

    var data = response;

    var cd = data.getElementsByTagName("CD");

    var table = "<table>";

        table += "<thead>";
        table += "<tr>";
        table += "<th>Title</th>";
        table += "<th>Artist</th>";
        table += "<th>Country</th>";
        table += "<th>Year</th>";
        table += "<th>Price</th>";
        table += "</tr>";
        table += "</thead>";
        table += "<tbody>";

        for ( var i = 0, len = cd.length; i < len; i++ ) {

            table += "<tr>";
            table += "<td>"+ cd[i].getElementsByTagName("TITLE")[0].firstChild.nodeValue +"</td>";
            table += "<td>"+ cd[i].getElementsByTagName("ARTIST")[0].firstChild.nodeValue +"</td>";
            table += "<td>"+ cd[i].getElementsByTagName("COUNTRY")[0].firstChild.nodeValue +"</td>";
            table += "<td>"+ cd[i].getElementsByTagName("YEAR")[0].firstChild.nodeValue +"</td>";
            table += "<td>$"+ cd[i].getElementsByTagName("PRICE")[0].firstChild.nodeValue +"</td>";
            table += "</tr>";

        }

        table += "</tbody>";
        table += "</table>";

    return table;
}

window.onload = function() {  
    "use strict";
    var button = document.getElementById("button");
    button.onclick = handleResponse;
};

To display data starting with the record from 1982 first, followed by 1985, and lastly 1988, how should I proceed?

Your insights on solving this issue are greatly appreciated!

Answer №1

To achieve this, you can transform cd into an array and then use the array's sort function. Thus, your modified handleXML function will look something like this:

function handleXML ( response ) {
    "use strict";

    var data = response;

    var cd = data.getElementsByTagName("CD");

    var table = "<table>";

        table += "<thead>";
        table += "<tr>";
        table += "<th>Title</th>";
        table += "<th>Artist</th>";
        table += "<th>Country</th>";
        table += "<th>Year</th>";
        table += "<th>Price</th>";
        table += "</tr>";
        table += "</thead>";
        table += "<tbody>";
        function sortByYear(a,b){
            return parseInt(a.getElementsByTagName("YEAR")[0].firstChild.nodeValue,10) - parseInt(b.getElementsByTagName("YEAR")[0].firstChild.nodeValue,10);
        }
        var sortedCD = Array.prototype.slice.call(cd);// converting XML object to array
        sortedCD=sortedCD.sort(sortByYear);//sorting based on the year element
        for ( var i = 0, len = sortedCD.length; i < len; i++ ) {

            table += "<tr>";
            table += "<td>"+ sortedCD[i].getElementsByTagName("TITLE")[0].firstChild.nodeValue +"</td>";
            table += "<td>"+ sortedCD[i].getElementsByTagName("ARTIST")[0].firstChild.nodeValue +"</td>";
            table += "<td>"+ sortedCD[i].getElementsByTagName("COUNTRY")[0].firstChild.nodeValue +"</td>";
            table += "<td>"+ sortedCD[i].getElementsByTagName("YEAR")[0].firstChild.nodeValue +"</td>";
            table += "<td>$"+ sortedCD[i].getElementsByTagName("PRICE")[0].firstChild.nodeValue +"</td>";
            table += "</tr>";

        }

        table += "</tbody>";
        table += "</table>";

    return table;
}

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

Create a JavaScript button that redirects to a different page within a React application

I am creating a div element using a for-loop and I want to link each div to the "/campaign" page with its respective id. When a div is clicked, I want it to navigate to the "/campaign/id" page and pass the id to the Campaign component. class Home extends ...

Is there a way in WebStorm to create a "virtual" folder for conveniently organizing and hiding config files, or perhaps a feature that allows for easily toggling visibility of certain files?

I have a strong dislike for having all my configuration files cluttering up the root directory. These files are usually set up at the beginning of a project and rarely need to be changed. While I can hide them in WebStorm, it becomes a hassle to unhide the ...

Is there a way to incorporate a JavaScript variable as the value for CSS width?

I created a scholarship donation progress bar that dynamically adjusts its width based on the amount donated. While I used CSS to handle the basic functionality, I am now trying to implement JavaScript for more advanced features. My goal is to calculate ...

Is there a way to ensure that a certain block of code in Typescript is executed only after an API call has been completed?

When making an API call, I need the code after the call to wait until the API call finishes. In my function called this.api_call, it calls the API and only returns an array returnValue once the call is complete. let returnValue = this.api_call(data); // ...

Retrieve an Excel file using Selenium through a URL, but only obtain JavaScript code instead

I am attempting to download an Excel file using its URL, but all I receive is JavaScript code. I'm unsure of how to retrieve the actual file instead of just the JS code. Here is my current code: # -*- coding: utf-8 -*- from selenium import webdrive ...

Creating a drop-down menu within an HTML table along with a D3 bar chart

How can I implement a drop-down menu allowing the user to choose a time interval for this HTML table and d3 bar chart? The time intervals needed are: Now, 24 hours, 48 hours, 72 hours, 1 week, and 1 month. I am relatively new to creating dynamic tables and ...

Enhanced security through dual authentication for MVC and WebAPI

I have developed two separate applications: MVC and WebAPI. In my MVC application, I make ajax requests to the WebAPI on certain pages. Additionally, I am using IdentityServer3 for authentication and authorization. Currently, I have implemented cookie-bas ...

Implementing alphabetical pagination in PHP

I am trying to implement alphabetical pagination in php, but I am facing a problem. When I click on any alphabet, the selected alphabet shows up in the address bar, however, the data starting from the selected alphabet is not displayed. Here are my databa ...

Detecting button clicks in different views using Backbone.js

In my current setup, I have a main parent view called View.A which is responsible for managing two child views - View.B and View.C. Specifically, View.B contains buttons that trigger events on that view. Configuration View.A View.B view.B.template. ...

Generated a hierarchical JSON structure from a dynamically generated form

My client has a unique page builder that allows them to create web forms using a convenient drag and drop interface. Currently, the data is output in a JSON format like this: { "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Missing CSS in dynamically loaded content on IE

I have been searching everywhere, but I just can't seem to find a satisfactory answer to this particular question. Whenever I load a few items on the page, they are displayed correctly at first. However, if a user decides to change the language, the ...

Retrieving the value of a radio button using jQuery and Ajax

Looking for assistance with radio buttons... <input type="radio" id="flip" name="flip" value="Head" checked="checked" /> Head <input type="radio" id="flip" name="flip" value="Tail" /> Tail I'm attempting to process a form with ajax, try ...

JavaScript code that retrieves an array containing only the deleted images from the information obtained from the edit product page

Currently, I am working on an edit product page in react with a node backend. The situation is as follows: Initially, the product had 4 images (a.png, b.png, c.png, d.png). I have made updates by removing the a.png image and adding a new image e.png. So ...

Enhancing time slot height on Fullcalendar V5: A step-by-step guide

Curious about adjusting the height of time slots in Fullcalendar V5 - any tips? ...

Concatenate data received from PHP to a JavaScript variable and return it

In my current app development project, I have the following code snippet. The variable valdat is sent to a specified URL, processed through a PHP file, and then returned to the app. How can I add the data displayed in the alert message to another variabl ...

Trouble with NodeJS: Unresponsive after AJAX post

Using NodeJS/Express with jQuery on the client side, I attempted to send a JSON object to the NodeJS/Express server for further processing. However, instead of receiving the expected "Hello World" message from the exports.findApiData function in index.js, ...

Using PHP as a data source, implement a feature in Google Maps that

I am currently working on incorporating an array of markers that are generated in PHP to a Google map. Below is the JavaScript code for my map: var map; var markers = []; var mapOptions = { //center: new google.maps.LatLng(locations[0].lat, locations[0 ...

Tips for adjusting the alignment of the Vuetify component "VDatePicker" based on the position of its parent component on the screen

Currently, I am utilizing the VMenu component from Vuetify which contains another Vuetify component called VDatePicker. The issue arises when clicking on a text field triggers the appearance of the calendar (VDatePicker). Normally, the VDatePicker componen ...

JavaScript OOP Function call not functioning in IE9

When using IE9, a JavaScript OOP Function call does not seem to work for me. Here is my code snippet: var newobj = new SAObject(); <input onclick="newobj.function()" /> Upon clicking the button, nothing happens. No alert is displayed, and it seem ...

Transforming multi-layered form data into a JSON array structure for seamless integration with application/json

I'm currently developing a Laravel application and facing an issue with the $controller->wantsJson() method in the back-end. This method returns TRUE only if the content type of the request is set to application/json. jQuery.ajax({ type: ...