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

The error message states that the element (0 , _dayjs.Dayjs) is not a valid function

I am currently in the process of replacing momentjs with dayjs. To start, I included the necessary dependencies: "dayjs":"1.10.7" Next, I imported dayjs like this: import { Dayjs } from 'dayjs'; To retrieve the start of the ...

Connecting the SignalR client to various servers

I am currently incorporating SignalR version 2.x into my ASP.Net MVC application, which is also using the same version of SignalR in my Angular client app. The ASP.Net MVC application is hosted at http://localhost:42080, while the Angular app is hosted at ...

I'm having trouble locating the module "script!foundation-sites/dist/foundation.min.js on Heroic."

This is the content of my webpack.config.js file: var webpack = require('webpack'); var path = require('path'); process.env.NODE_ENV = process.env.NODE_ENV || 'development'; module.exports = { entry: [ 'script!jque ...

Developed a hierarchical JSON format using a JavaScript array

I am aiming to generate a properly structured nested JSON file from an array, with unique key values. Currently, I can only output the JSON without any nesting. The desired structure to be displayed in the console is : { "Key" : "data1", "header" ...

How can an Angular Component be created in the browser using the standard method?

Attempting to develop a basic Angular example using JS/ESM. It has been some time since working within the angular environment, and there appear to be two primary choices: Utilizing the UMD lib (preferably to be avoided) Using the ESM2015 folder and loadi ...

Steps to link a specific section of a Google pie chart:

I have a question that may be a little confusing, so let me explain. I recently used Google Charts to create a simple pie chart and it worked perfectly. Now, I am trying to figure out how to link each section/part of the pie chart to display a jQuery moda ...

Unexpected Issue with Lightbox2 Functionality in Chrome Browser

Not too long ago, I reached out here for the first time with a similar issue: my image gallery on my art portfolio site was malfunctioning in Chrome, yet worked fine in Microsoft Internet Explorer and Edge. Thanks to some incredibly helpful and patient in ...

What issue is present with this AJAX query?

Can you help me figure out where I went wrong with this AJAX code example that I'm trying to learn from? function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new ...

Setting the CSS position to fixed for a dynamically generated canvas using JavaScript

My goal is to fix the position style of the canvas using JavaScript in order to eliminate scroll bars. Interestingly, I can easily change the style using Chrome Inspector with no issues, but when it comes to implementing it through JS, I face difficulties. ...

Trouble with AJAX Post Request: Missing JSON Response

Below is the AJAX request I have created: var data = modalDom.find("form").serializeObject(); data["returnJson"] = true; $.ajax({ type: "POST", url: "/companies/edit/", data: data, dataType: "JSON", success: function (result) { ...

React function causing website to freeze upon dispatch

I created a function in the child component to handle checkbox selection and trigger setDispatch(true). Unfortunately, whenever I check the checkbox, the website freezes and stops responding until I close and reopen it. Here is the function: const [ ...

Invoke a PHP function within a Bootstrap Modal using AJAX technology

My webpage features a list of users generated through a PHP loop. By clicking on each user's name, a Bootstrap Modal appears showcasing more information about the user. The hyperlink for each user looks like this: <a href="#user" data-toggle="mod ...

Having trouble deleting a Repeatable Job from the Bull queue in Node.js

Upon attempting to utilize the removeRepeatableByKey method, I encountered an error stating that removeRepeatableByKey is not a function. Specifically, it mentioned that queue_1.taskQueue.removeRepeatableByKey is not a function. Furthermore, I am facing d ...

What is the method for executing a specific task using grunt.registerTask()?

My grunt tasks are registered like this - grunt.registerTask('regenerateSources', ['clean:local', 'bower', 'uglify']); When I run grunt regenerateSources, it executes the clean, bower and uglify tasks. But is there ...

Setting up ESLint for TypeScript with JSX configuration

I am encountering problems with TypeScript configuration. Below is the code snippet from my tsconfig.json: { "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLib ...

The json_decode function results in a null value

I save encrypted collections in a database, but when I attempt to decipher them, they come back as null. [{"id":13,"qty":"1"}] The arrays are encrypted using PHP, so I am unsure of what the issue could be. Appreciate any help. ...

Using $stateParams injection for unit testing Angular applications with Karma

Here is the starting point for the controller code: angular .module('hc.hotelContent') .controller('NameLocationController', nameLocationCtrlFn); //Todo change hotelDataService nameLocationCtrlFn.$inject = ['$stateParams', &a ...

Issue occurred while trying to update the MySQL database with an HTML form and Ajax integration

I am facing an issue with my form that uses a drop-down box and a hidden form field to send information to a PHP page. Everything works as expected when I submit the form directly to the PHP page, but when I try using AJAX to pass the information, it doesn ...

The use of 'import ... =' is restricted to TypeScript files

Error: Oops! Looks like there's a hiccup in the code... 'import ... =' is exclusive to TypeScript files. Expecting '=' here. Don't forget the ';'. Unexpected keyword or identifier popping up! package.json ...

"What could be the reason why the color property is not being applied to this

I have been attempting to change the color of an icon by using the color property, but for some reason, it is not applying as expected. Here is the code snippet I am working with: "& .MuiListItemIcon-root": { color: "red" }, ...