No error reported upon trying to render json output

I'm having an issue where the following code is not displaying any output. Can someone help me identify what mistake I might be making?

This is the HTML file:

<head>
<script type = "text/javascript">
function ajax_get_json() {
    var hr = new XMLHTTPRequest();
    hr.open("GET", "mylist.json", true);
    hr.setRequestHeader("Content-type: application/json", true);

    hr.onreadystatechange = function() {
        if (hr.readyState == 4 && hr.status == 200) {
            var data = JSON.parse(hr.responseText);
            var results=document.getElementById("results");
            results.innerHTML = data.user;
        }
    }
    
    hr.send(null);
    results.innerHTML = "requesting...";
} 
</script> 
</head>

<body>

    <div id="results"></div>
    <script type = "text/javascript">ajax_get_json();</script>

</body>

And here is the JSON file content: { "user":"John", "age":22, "country":"US" }

Answer №1

XMLHTTPRequest() should actually be written as XMLHttpRequest(). Here is a snippet of the JavaScript code:

function request() {}

request();

The HTML part looks like this:

<script src="file.js"></script>

When you use

var data = JSON.parse(hr.responseText);
, you are dealing with an object. You can iterate through the object using:

for(var key in obj) {}

and then display both the key and obj[key] in the innerHTML to see the result. Here is the complete JavaScript file:

function request() {
  var hr = new XMLHttpRequest();
  hr.onreadystatechange = function() {
    if (hr.readyState == 4 && hr.status == 200) {
      var data = JSON.parse(hr.responseText); // object
      var results = document.getElementById("results");
      results.innerHTML = "";
      for(var key in data) {
        results.innerHTML += key + " " + data[key] + "<br>";
      }

    }
  }
  hr.open("GET", "mylist.json", true);
  hr.send();
  results.innerHTML = "requesting...";
}

request();

(Make sure to provide specific titles for your questions - How to ask)

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

"Jest test.each is throwing errors due to improper data types

Currently, I am utilizing Jest#test.each to execute some unit tests. Below is the code snippet: const invalidTestCases = [ [null, TypeError], [undefined, TypeError], [false, TypeError], [true, TypeError], ]; describe('normalizeNames', ...

Is there a way to identify and remove empty spaces and carriage returns from an element using JavaScript or jQuery?

Is there a way to easily remove empty elements from the DOM by checking if they contain only whitespace characters or nothing at all? I am attempting to use $.trim() to trim whitespace in empty elements, but some are still returning a length greater than ...

Traversing through elements with unique IDs in SwiftyJSON that are not part of an array

When calling an API, I sometimes receive an array of simple JSON objects. I handle these by parsing them using a basic "for i in count" loop and appending json[i]["city"] with SwiftyJSON. For instance: [{"city":"Lakefront","code":"NEW","country":"United S ...

What steps can be taken to activate a class upon a click event?

I have successfully implemented a hover function to change the background color on my element, but now I need to add an additional functionality to make the class active on click event as well. I have been struggling to find a solution for this issue and ...

Halt! There is a Syntax Error: anticipating an expression, but instead received the keyword 'for'

I'm encountering an issue with this code. I need help to figure out how to print a loop inside dynamiHTML. Can anyone assist me? function createDiv(data){ var dynamicHTML = ''; alert(data.res2.length); dynamicHTML += '<div ...

What is the reason behind caching form data in an ajax call?

After the first successful submission, I am facing an issue where the original form data is being re-sent even when new values are submitted for a second attempt. How can I reset and reload the data to avoid this problem? I have tried several approaches i ...

Interactive quiz program based on object-oriented principles

As I work on developing a quiz app using JavaScript, everything seems to be going well. However, I've encountered an issue with validation where my code is validating the answers twice - once with the correct answer from the previous question and agai ...

What is the proper way to provide parameters in a GET request using Axios?

Recently, I have been attempting to include the api_key in the get request parameter using axios Below is the snippet of my code: const instance = axios.create({ baseURL: "https://api.themoviedb.org/3" }); export function crudify(path) { function get ...

What is causing the issue with useForm not being identified as a function?

error image Why is this error occurring when attempting to use useForm: ⨯ src\app\journal\page.tsx (18:53) @ useForm ⨯ TypeError: (0 , react_hook_form__WEBPACK_IMPORTED_MODULE_5__.useForm) is not a function at Page (./src/app/journal/pa ...

The ESLint rule "eqeqeq" configuration is deemed incorrect

After successfully running eslint with the provided .eslintrc file, I encountered an issue when making a simple change to use 'standard' instead of 'airbnb-base' as the extend: module.exports = { root: true, parser: 'babel-esl ...

Add a checkbox element to a web API using ReactJS

I'm currently learning react and encountering an issue with checkboxes that I can't seem to resolve. I am working on a modal for updating and inserting data in a .net core web api, which is functioning correctly. However, within the app, I'm ...

Ensuring the security of a PHP application hosted on a Compute Engine virtual machine to connect with Google Cloud Storage (G

Recently, I set up a Google Compute Engine (GCE) instance with a service account that has access to cloud storage. On this instance, there is a php application that needs to move uploaded files to a specific bucket in Google Cloud Storage. When creating t ...

Displaying content on a webpage using PHP, AJAX, and HTML

Looking to update my current form setup. I have a basic Form below: <form action="" method="POST"> <input type="button" value="Generate Numbers" onclick="on_callPhp1()"/> </form> Accompanied by this javascript code: <script type="te ...

How can you utilize a previously opened window from another page in JavaScript?

One of my challenges involves managing windows in a JavaScript environment. When I open a child window using window.open("http://foobar","name"), it reuses the same window when opened with the same name, which is exactly what I want. However, if the origi ...

Is it possible to delete an element from an HTML form?

I'm facing an issue with removing an element from my HTML form during the loading process. The specific element in question is as follows: <input type="hidden" name="testToken" value="1000ad"></input> Here's what I've tried so ...

IE8 - "object does not exist or is undefined" error

Below is the HTML code snippet: <td style="vertical-align: bottom;"><div id="resultCount">n.v.</div></td> Accompanied by this JavaScript code: function processResultCount(data) { $("#resultCount").html(formatNumber(data.res ...

Is there a way to implement request-specific global variables for individual websocket connections in a Node.js application, similar to using res.locals for

Currently, I'm working on creating global variables within the io.use method of the socket.io server-side library. The goal is to have variables that are accessible throughout the entire request lifecycle for websockets. My setup involves using the ex ...

What is the most effective way to send multiple values through the <option> value attribute?

Currently, I am in the process of creating an online shopping item page. To display all the necessary information about an item (such as price, image, name, etc.), I use the 'item_id' to loop through a database containing item info. Additionall ...

Implementing hover effect triggered by keyboard input

Is there a way to create a hover effect on a div when a specific key is pressed on the keyboard using jQuery? <div id="d-up" class="button"></div> Appreciate any help with this! Thank you. ...

Creating a stunning HTML 5 panorama with GigaPixel resolution

Interested in creating a gigapixel panorama using HTML 5 and Javascript. I found inspiration from this example - Seeking advice on where to begin or any useful APIs to explore. Appreciate the help! ...