Unable to retrieve data from JSON file using Ajax request

Trying to populate an HTML table with data from an external JSON file is proving to be a challenge. Despite making an AJAX request using pure JavaScript, nothing happens when the "Test" button is clicked. Take a look at the JSON data:

{   "row":[

 {
     "ID" : "2",
     "FirstName" : "John",
     "LastName" : "Test",
     "DOB": "03-12-1959",
     "Gender":"M"
    },

     {
     "ID" : "3",
     "FirstName" : "Helen",
     "LastName" : "Test",
     "DOB": "03-12-1959",
     "Gender":"M"
    }

]
}

An excerpt from the HTML code:

<button onclick="loadJSON()">Test</button>
<table class="test-table">
  <thead>
    <tr>
      <th>ID</th>
      <th>First Name</th>
      <th>Last Name</th>
      <th>DOB</th>
      <th>Gender</th>
    </tr>
  </thead>

  <tbody id="data">
    <tr>
      <td><label for="row1"></label>123</td>
      <td>John</td>
      <td>Doe</td>
      <td>02-15-1982</td>
      <td>M</td>
    </tr>
  </tbody>
 </table>

The JavaScript part of the code:

function loadJSON(){
     var data_file = "test.json";
            var http_request = new XMLHttpRequest();
            try{
               // Opera 8.0+, Firefox, Chrome, Safari
               http_request = new XMLHttpRequest();
            }catch (e){
               // Internet Explorer Browsers
               try{
                  http_request = new ActiveXObject("Msxml2.XMLHTTP");

               }catch (e) {

                  try{
                     http_request = new ActiveXObject("Microsoft.XMLHTTP");
                  }catch (e){
                     // Something went wrong
                     alert("Your browser broke!");
                     return false;
                  }

               }
            }

            http_request.onreadystatechange = function(){

               if (http_request.readyState == 4  ){

                  var jsonObj = JSON.parse(http_request.responseText);
                  var tr, td;
                  var tbody = document.getElementById("data");

    // loop through data source
    for (var i=0; i<jsonObj.row.length; i++) {
        tr = tbody.insertRow(tbody.rows.length);
        td = tr.insertCell(tr.cells.length);
        td.setAttribute("align", "center");
        td.innerHTML = jsonObj.row[i].ID;
        td = tr.insertCell(tr.cells.length);
        td.innerHTML = jsonObj.row[i].FirstName;
        td = tr.insertCell(tr.cells.length);
        td.innerHTML = jsonObj.row[i].LastName;
        td = tr.insertCell(tr.cells.length);
        td.innerHTML = jsonObj.row[i].DOB;
        td = tr.insertCell(tr.cells.length);
        td.innerHTML = jsonObj.row[i].Gender;

    }

}

http_request.open("GET", data_file, true);
http_request.send();
  } 

If you have any insights on what could be going wrong or how to fix it, your help would be greatly appreciated.

Answer №1

You've missed a closing bracket } in your function just before http_request.open()...
Try adding this one and it should work.

HTML file

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <button onclick="loadJSON()">Test</button>
    <table class="test-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>DOB</th>
                <th>Gender</th>
            </tr>
        </thead>
        <tbody id="data">
            <tr>
                <td>
                    <label for="row1"></label>123</td>
                <td>John</td>
                <td>Doe</td>
                <td>02-15-1982</td>
                <td>M</td>
            </tr>
        </tbody>
    </table>
    <script type="text/javascript">
    function loadJSON() {
        var data_file = "test.json";
        var http_request = new XMLHttpRequest();
        try {
            // Opera 8.0+, Firefox, Chrome, Safari
            http_request = new XMLHttpRequest();
        } catch (e) {
            // Internet Explorer Browsers
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");

            } catch (e) {

                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
                }

            }
        }

        http_request.onreadystatechange = function() {

            if (http_request.readyState == 4) {

                var jsonObj = JSON.parse(http_request.responseText);
                var tr, td;
                var tbody = document.getElementById("data");

                // loop through data source
                for (var i = 0; i < jsonObj.row.length; i++) {
                    tr = tbody.insertRow(tbody.rows.length);
                    td = tr.insertCell(tr.cells.length);
                    td.setAttribute("align", "center");
                    td.innerHTML = jsonObj.row[i].ID;
                    td = tr.insertCell(tr.cells.length);
                    td.innerHTML = jsonObj.row[i].FirstName;
                    td = tr.insertCell(tr.cells.length);
                    td.innerHTML = jsonObj.row[i].LastName;
                    td = tr.insertCell(tr.cells.length);
                    td.innerHTML = jsonObj.row[i].DOB;
                    td = tr.insertCell(tr.cells.length);
                    td.innerHTML = jsonObj.row[i].Gender;

                }

            }
        }; // <----- This is the one you left off

        http_request.open("GET", data_file, true);
        http_request.send();
    }
    </script>
</body>

</html>

JSON file

{
    "row": [

        {
            "ID": "2",
            "FirstName": "John",
            "LastName": "Test",
            "DOB": "03-12-1959",
            "Gender": "M"
        },

        {
            "ID": "3",
            "FirstName": "Helen",
            "LastName": "Test",
            "DOB": "03-12-1959",
            "Gender": "M"
        }

    ]
}

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

A variety of menu items are featured, each one uniquely colored

In the user interface I developed, users have the ability to specify the number of floors in their building. Each menu item in the system corresponds to a floor. While this setup is functional, I am looking to give each menu item a unique background color ...

Converting a cursor object to XML or JSON on an Android platform: Step by step guide

Are there any libraries available to directly convert a Cursor object to XML or JSON? For instance, if we have a table with two columns: id and name. When I retrieve a cursor object from the database, is it possible to convert it into <XML> <id& ...

Using `v-if` with a Vuex getter

Currently, I am utilizing a vuex getters called isLoggedIn to verify whether a user is logged in or not. <div v-if="isLoggedIn" class="ml-2 py-2 group relative">...</div> data() { return { isLoggedIn: this.$store. ...

Angular error: Trying to assign a value of type ArrayBuffer to a string type

Is there a way to display a preview of a selected image before uploading it to the server? Here is an example in HTML: <div id="drop_zone" (drop)="dropHandler($event)" (dragover)="onDragover($event)"> <p>drag one or more files to ...

java.lang.RuntimeException: Activity ComponentInfo in Android could not be launched

Currently facing an issue while attempting to parse a JSON object Value on this website. I keep receiving a runtime error that states: Unable to start activity componentinfo: Illegal character in URL. Here is the code snippet: Attempting to address the &a ...

Is it possible to create tags in Material UI Autocomplete using events other than just pressing the 'Enter' key?

In my current project, I am utilizing the freesolo Autocomplete feature. My specific requirement is to create tags when input text is followed by commas or spaces. Currently, tags are created on the Enter event by Autocomplete, but I am looking for a way t ...

Encountering the error "Cannot read property 'header' of undefined" while conducting tests on Nodejs using supertest

In my server.js file, I have set up my express app. I tried to run a demo test in my test file using express, but unfortunately, the test did not run successfully. const request = require('supertest'); const express = require('express' ...

Utilizing AJAX and JavaScript to generate a table using the AJAX response and placing it within a <div> element

I am currently passing the response of this action in text form, but I would like to display it in a table format. Is there a way to do this? function loadAditivos(){ $('#aditivoAbertoInformacoesTexto').html('<div id="loaderMaior ...

Issue with using puppeteer for testing applications

Having an issue as a beginner in JavaScript, I'm struggling to solve this error. I am fetching data from a website using puppeteer and trying to verify if it's the correct one: const puppeteer = require('puppeteer'); (async () => { ...

Issue with Build System CTA's/Callback function functionality not operational

I have encountered an issue with my build/design system. Although everything works fine during development, when I publish my package and try to use the callback function, it does not return the necessary data for me to proceed to the next screen. I tried ...

One omission of argument 1 has been detected in the search_model::autocomplete() function

This is the controller for the search.php file. public function login() { $email=$this->input->post('email'); $password=md5($this->input->post('password')); $result=$this->search_model->login($email,$passw ...

How does handleChange receive the value as an input?

Greetings! Currently, I am delving into the world of React and JavaScript. I am experimenting with a Table Component demo that can be found at the following link: https://codesandbox.io/s/hier2?file=/demo.js:5301-5317 In the demo, there is a function defi ...

Utilize Vue to localize the click events of buttons on the webpage

I have a scenario where I have several buttons on a page, and when I click one to toggle its text, all of the buttons change. How can I utilize VUE to isolate functionality and make each button's @click event only affect the clicked button? In the cod ...

Leverage node rework CSS directly within your browser for seamless website

Looking to utilize the reworkcss/css library in the browser. Downloaded version 2.0.0 from GitHub and installed necessary packages with npm install. Attempted using requireJS, which supports processing the CommonJS Module Format by requiring index.js, bu ...

Converting JSON attributes into a collection of string values

In my project, I utilize Java Spring for development tasks. A requirement I have is to efficiently parse JSON data into corresponding Java classes. Here is an example snippet of the JSON data: [ { "Id":"aaa1" "Data1 ...

Error: Jest encounters an unexpected token 'export' when using Material UI

While working on my React project and trying to import { Button } from @material-ui/core using Jest, I encountered a strange issue. The error message suggested adding @material-ui to the transformIgnorePatterns, but that didn't resolve the problem. T ...

How to open a print preview in a new tab using Angular 4

Currently, I am attempting to implement print functionality in Angular 4. My goal is to have the print preview automatically open in a new tab along with the print popup window. I'm struggling to find a way to pass data from the parent window to the c ...

Using Axios in Vuejs to prompt a file download dialog

I am currently working on figuring out how to trigger a file download dialog box after receiving an Ajax request from the Flask server using Axios. Here is my current client-side code snippet: <script> export default { ... exportCSV: function() { ...

Transform Json data into a C# collection

I am encountering an issue while trying to deserialize JSON into a collection of C# objects. The error message I am receiving is as follows: {"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'Sys ...

Sorting elements in an array based on an 'in' condition in TypeScript

I am currently working with an arrayList that contains employee information such as employeename, grade, and designation. In my view, I have a multiselect component that returns an array of grades like [1,2,3] once we select grade1, grade2, grade3 from the ...