Struggling to retrieve information from an XML file

As a newcomer to XML and JSON, I am facing difficulties in displaying my data in an HTML div. I am attempting to extract data from the xml api and showcase it within my div.

Unfortunately, nothing is showing up in my div. Please excuse the messy code. If you're interested, you can view how the XML file looks like by visiting this link.

UPDATE After switching to a json data source, I've managed to display my data. However, only two lines of data are visible and I'm unsure why this is happening.

    var json4day; //global variables - values accessible by all functions

$(function() {
    Load4day(); //calling function to load data****
});

function Load4day(){
    $.ajax({
        url: "https://api.data.gov.sg/v1/environment/4-day-weather-forecast",
        dataType: "json",
        headers: {"api-key": "nVjYBrTc4KMLNjJQrKwlc0Be9V5zFYXZ"}
    })
    .done(function(json) { 
        json4day=json;
        ShowData();
    })
    .fail(function() {
        console.log("error");
    });
}



function ShowData(){
    console.log("Displaying data");
    var tforecasts=json4day.items[0].forecasts.length;
    console.log(tforecasts);
    for(var i=0;i<tforecasts;i++){
        var fc=json4day.items[0].forecasts[i].forecast;
        var date=json4day.items[0].forecasts[i].date;
        var icon=json4day.items[0].forecasts[i].relative_humidity;
        var html="<div data-index='"+i+"'>"+date+"<br>"+fc+"<br></div>";
        
        $(".content1").append(html);

    }
}

I am aiming to present my data in the following div:

<div id="main1">
    <div class="b1">

        <div class="4hr">
            <p class="t1">4 Hour Forecast </p>

            <div id="target">
            click here
            </div>

        </div>

    </div>

Answer №1

It's clear that the issue at hand is you are manipulating the wrong object.

The response from your ajax call is not in JSON format, but rather it now returns an HTMLCollection object, which behaves differently than JSON.

After Update:

Your code updates the content as follows:

$(".content1").append(html);
// $(".content1").html(html); // Replaces the 'content' in 'content1' class 
// $(".content1").append(html2); // Appends the same 'content' again
// $(".content1").html(html2); // Replaces the 'content' in 'content1' class 

If you remove the last 3 lines, everything should work correctly.

There is a significant distinction between JQuery.html() (which replaces the content within the specified element) and JQuery.append() (which adds the content to the end of the specified element).

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/QAPage">

<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
        var json4day; //global variables - all functions can read and store values inside

        $(function () {
            $(".content1").html("");
            Load4day(); //call function to load data****
        });

        function Load4day() {
            //2 hour code here
            $.ajax({
                url: "https://api.data.gov.sg/v1/environment/4-day-weather-forecast",
                dataType: "json",
                headers: {
                    "api-key": "nVjYBrTc4KMLNjJQrKwlc0Be9V5zFYXZ"
                }
            })
                .done(function (json) { //tween max oncomplete
                    json4day = json;
                    ShowData(); //load PSI*****
                })
                .fail(function () {
                    console.log("error");
                });
        }

        function ShowData() {
            console.log("Show data");
            console.log(json4day);
            var tforecasts = json4day.items[0].forecasts.length;
            console.log(tforecasts);
            for (var i = 0; i < tforecasts; i++) {
                var fc = json4day.items[0].forecasts[i].forecast;
                var date = json4day.items[0].forecasts[i].date;
                var icon = json4day.items[0].forecasts[i].relative_humidity;
                //  console.log(lt);
                var html = "<div data-index='" + i + "'>" + date + "<br>" + fc + "<br></div>";
                var html2 = "<div data-index='" + i + "'>" + date + "<br>" + fc + "<br></div>";
                $(".content1").append(html);
                //$(".content1").html(html);
                //$(".content1").append(html2);
                //$(".content1").html(html2);    
            }
        }
    </script>
</head>

<body>
    <div id="main1">
        <div class="b1">
            <div class="4hr">
                <p class="t1">4 Hour Forecast </p>
                <div id="target">
                    click here
                </div>
            </div>

            <div class="content1">some text</div>

            <!--<iframe width="600" height="400" src="https://data.gov.sg/dataset/weather-forecast/resource/4df6d890-f23e-47f0-add1-fd6d580447d1/view/91f4e399-5a83-4cab-9491-09464db88661" frameBorder="0"> </iframe>-->
        </div>
</body>

</html>

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

Having trouble getting JSON data to display in an Ionic HTML file

After successfully retrieving data from my API and logging it in the console, I am facing difficulties accessing it through my HTML file. Despite looking into other questions for a solution, I still couldn't figure out why it isn't working. Here ...

What is the solution for excluding 0s in my javascript code?

I am working on a code to calculate the average of four numbers entered by the user, but I want to exclude zeros from the calculation. Currently, the code successfully excludes one zero, but I am struggling to exclude multiple zeros. My initial approach ...

issues with adding class to div element

I have a div section that contains various movie items and overlay elements. <div class="overlay"> <a title="yes" href="#"><div class="yes"></div></a> <a title="no" href="#"><div class="no"></div>< ...

Npm is unable to locate the package.json file in the incorrect directory

Hello, I am currently in the process of setting up webpack. I have all the configurations ready, but when I attempt to execute webpack in my terminal, it looks for the package.json file in the incorrect location. Is there a way for me to modify the path ...

What is the best way to include dynamic query parameters in the src attribute of a <script> tag?

As I develop a basic asp.net application, I encountered a situation where I needed to include a script with a dynamic query parameter in my aspx page. For instance: <script src="../javascript/script.js?v=#var#" type="text/javascript"></script> ...

What is the reason for the .foo a:link, .foo a:visited {} selector taking precedence over the a:hover, a:active {} selector in CSS?

Sample code: http://jsfiddle.net/RuQNP/ <!DOCTYPE html> <html> <head> <title>Foo</title> <style type="text/css"> a:link, a:visited { color: blue; } a:hover, a:active { ...

Error message: The md-autocomplete function is throwing a TypeError because it cannot read the property 'then' of an undefined object

I am encountering an issue with the md-autocomplete component from angular material. Here is my code snippet: <md-autocomplete required md-search-text="searchTxt" md-selected-item-change="setModelValue(item.name)&q ...

Creating JasperReports in Java using a JSON file

Having trouble with generating JasperReport using Java. The DataSource is not being recognized, resulting in all values being null and the subReport not appearing. I've set up a JSONDataAdapter with the option 'Use the report JSON expression whe ...

Revamp the component onclick functionality in ReactJS

Within my component, I have an onClick method defined. This method makes a call to the backend and fetches some data. However, the values retrieved from this call are only reflected after refreshing the browser. Is there a way to re-render my component wit ...

What is the best way to replace a CSS Background that is already marked as important?

Attempting to change the background of a website using Stylish, but encountering issues. The existing background css on the website includes an !important rule which is preventing Stylish from taking effect. Here is my code: body { background-image: n ...

Ensure that an element exists in Selenium before proceeding with actions

Currently, I am undergoing testing with the Selenium web driver and one of the requirements is to wait for my object to be defined on the page. Important: There are no visible changes in the DOM to indicate when my object is ready, and it's not feasib ...

File.type cannot be obtained in IE 11 and IE Edge due to compatibility issues

"change .btn-file :file" : "getfileinfo", getfileinfo: function(e){ var fileInput = document.getElementById('fileupload'); var file = fileInput.files[0]; if(!file || (file.type != 'text/plain' && file.type != ' ...

When I include a class in a checkbox label, the CSS ceases to function properly

Apologies for my lack of understanding, but I am facing an issue with applying an attribute to a label element with class "c". It seems to work fine with other objects, like buttons, but not with labels. I cannot figure out why such a simple thing is not w ...

Gather information from every user and display their user ID in an HTML table, allowing for updates through a button

Can anyone help me create a table like the one shown here: https://i.sstatic.net/Hj4T9.png The table should fetch data from my firebase database. Here is the structure of my requests database: https://i.sstatic.net/0lJGa.png. I've been trying to mo ...

What is the best way to set jade as a global variable in a node.js Express application?

Currently, the routing function shown below is operational: exports.summary = function(req, res, next) { var jade = require('jade'); res.render('myView', { main: jade.renderFile('./views/summary.jade') }); }; The ...

What are the steps to modify the text color in WKWebView?

I've customized my ViewController to include a WKWebView, where I load my content from both .html and .css files. The result resembles a controller for reading books within the Apple Books app. do { guard let filePath = Bundle.main.path(fo ...

Switch the accordion to open or close

I am struggling to create an accordion menu that toggles open and close using the same button. Right now, it only opens and I cannot figure out how to make it close as well. Below is my current code, or you can view it on jsFiddle: http://jsfiddle.net/nd ...

Guidelines for sending an array from a Laravel Controller through AJAX and generating a button based on the received data

Before making a selection, I click on the Color button: <form class="form form-variant"> {{ csrf_field() }} <button type="submit" class="btn btn-success che ...

There was an issue with the v-on handler that threw an error: "Error: Reference.set failed because the first argument contains undefined."

I'm struggling to pinpoint where exactly the error occurs. Despite numerous attempts to log all the input data for the database, everything seems to have values... https://i.sstatic.net/TBk1L.png The goal is to store the current message in the datab ...

What is the best way to use CSS to set text color as a background image?

I need the output to look like the image displayed below. Below is my code snippet: https://jsfiddle.net/sidh_41/t7sbc2zf/ .card-text { background: #1f2227ab; } <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min. ...