`How can I fetch external JSON data using an AJAX request in an HTML document?`

Testing the functionality of this HTML page by creating a dummy JSON file, but encountering an issue with loading the data via AJAX request. The specific error message received is:

Uncaught ReferenceError: data is not defined.

Struggling to call and integrate the JSON file within the HTML page despite various attempts. Referenced this source for guidance: view-source

index.html

<!DOCTYPE HTML>
<html>
<head>
  <title>Matter Timeline</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <script type="text/javascript" src="jquery.min.js"></script>
  <script type="text/javascript" src="bootstrap.js"></script>
   <!-- load handlebars for templating, and create a template -->
  <script src="dist/handlebars-v4.0.11.js"></script>
  <script id="item-template" type="text/x-handlebars-template">
      {{target}} 
      <font color="#229954"><b>{{status_green}}</b></font>
      <font color="#A93226"><b>{{status_red}}</b></font>
      <br/>
      <font size="2" color="#2874A6">{{action}}</font> 
      <font size="2" color="#2874A6"><i>{{user}}</i></font> <br/> 
      <span class="tooltip-date">{{datetime}}</span>
  </script>

  <script src="dist/vis.js"></script>
  <link href="dist/vis-timeline-graph2d.min.css" rel="stylesheet" type="text/css" />
  <script>

    function resettimeline() {
        document.location.reload();
    };
  </script>     
</head>

<body>
<p>
  <center><h2>Matter Timeline</h2></center>
</p>
<div id="visualization"></div>

<script type="text/javascript">
  var groups = new vis.DataSet([
    {id: 0, content: 'Process/Task', value: 1},
    {id: 1, content: 'Req/Matter/Doc', value: 2}
  ]);

  var source = document.getElementById('item-template').innerHTML;
  var template = Handlebars.compile(document.getElementById('item-template').innerHTML);

  $.ajax({
    url: 'http://127.0.0.1:8887/data.json',
    dataType: "json",
    success: function(data) {
        //handle you data here
    }
  });

  // create visualization
  var container = document.getElementById('visualization');
  var options = {
    // option groupOrder can be a property name or a sort function
    // the sort function must compare two groups and return a value
    //     > 0 when a > b
    //     < 0 when a < b
    //       0 when a == b
    groupOrder: function (a, b) {
      return a.value - b.value;
    },
    orientation: {
        axis: 'top',
        item: 'top'
    },
    height: "85vh",
    template: template
    //timeAxis: {scale: 'day', step:3}
  };


  var timeline = new vis.Timeline(container);
  timeline.setOptions(options);
  timeline.setGroups(groups);
  timeline.setItems(data); 


  timeline.on('doubleClick', function (properties) {
    window.open('the_doc_url', 
                'newwindow', 
                'width=1000,height=600'); 
    return false;
  });

</script>
<br/>
<a href="javascript:resettimeline()">Fit to Width</a>
</body>
</html>

data.json

{
  "data": [
    { 
        id: 1, group: 0, 
        target: 'Request',
        action: 'from',
        user: 'SAS',
        datetime: '7/10',
        title: '<span class="tooltip-date">Date: 7/10/2017 09:00</span><br/>Req ID: R123',
        start: new Date(2017,9,7, 9,0,0,0)
    },
    { 
        id: 2, group: 0, 
        target: 'Request',
        action: 'by',
        user: 'Alice',
        datetime: '8/10',
        title: '<span class="tooltip-date">Date: 8/10/2017 13:34</span><br/>Req ID: R123',
        start: new Date(2017,9,8, 12,30,0,0)
    }
  ]
}

Answer №1

AJAX stands for "Asynchronous JavaScript And XML", and it appears that the asynchronous aspect was overlooked. The section of code utilizing the "data" variable is located outside the callback function, causing this variable to either not exist or have an undefined value.

It is essential to handle the JSON data after receiving it, similar to the following approach (which could benefit from some cleaning up):

$.ajax({
    url: 'http://127.0.0.1:8887/data.json',
    dataType: "json",
    success: function(data) {
        // Handle your data processing here

            // Create visualization
            var container = document.getElementById('visualization');
            var options = {
              groupOrder: function (a, b) {
                return a.value - b.value;
              },
              orientation: {
                  axis: 'top',
                  item: 'top'
              },
              height: "85vh",
              template: template
            };

            var timeline = new vis.Timeline(container);
            timeline.setOptions(options);
            timeline.setGroups(groups);
            timeline.setItems(data.data); 

            timeline.on('doubleClick', function (properties) {
                window.open('the_doc_url', 
                            'newwindow', 
                            'width=1000,height=600'); 
                return false;
            });
      }
});

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 Ashima Perlin noise shader seems to be malfunctioning on newer releases of Three.JS

Seeking help on SO as a final attempt to resolve an issue with the latest Three.JS, as my Google searches have turned up empty. I am working with the Ashima Perlin noise shader (examples here) - Everything runs smoothly with version 48 of Three.JS, but w ...

What is the best way to retrieve data from PHP and format it into JSON for use in my jQuery script?

I need help formatting the data returned to jQuery from a query. The specific format I want is: var externalDataRetrievedFromServer = [ { name: 'Bartek', age: 34 }, { name: 'John', age: 27 }, { name: 'Elizabeth', ...

Is it better to conceal modals or completely eliminate them from the DOM when working with React?

I am currently developing a React application that involves multiple modals, with only one active at a time and no nested modals. I am torn between two approaches for handling the showing and hiding of these modals: The first approach involves having a b ...

Executing a query with a `has many` relationship in MongoDB: Step-by-step guide

In my setup with Node, Express, and backbone, I am successfully retrieving records from MongoDB collections using simple queries. However, I am struggling to understand how to query more complex data, such as the one below: db.employees.aggregate( [ ...

Encountering a null value after making changes to the state in Reactjs

I'm currently working on a drag-and-drop web application using reactjs. The issue I'm encountering is that when I initiate the drag action, it triggers the handleDragStart function to update the state variable called selectedCard. However, when I ...

How to retrieve a variable number from a JavaScript string

In an ASP.NET environment, I am working with a string called ctl00_ContentPlaceHolder1_lstViewFormulas_ctrl06_lblCountDown, which will be passed into a JavaScript function using the sender parameter from my button control... <asp:Button ID="buttStartTi ...

Code snippet in webpage body

Hey there, I could really use some assistance: I currently have the following: A) Login.html B) Documentation.html C) Base.html Within the login page, there is a form with fields for User and Password. In Documentation, there are links to various folder ...

Incorporate additional text to the downloads hyperlink using jquery

Is it possible to achieve this using jQuery since I am unable to directly modify the HTML markup? I am looking to append download.php?file= to a URL without replacing the entire href attribute. Here's an example of what I'm trying to achieve: & ...

The error occurring in the React app is a result of the page rendering prior to the API data being fetched

Utilizing the following component for my Nav, I aim to showcase the current weather based on the user's location. However, an issue arises as the page is being rendered before retrieving data from the openWeather API. import React, { useState, useEffe ...

Which tools should I combine with Angular for developing both Android and iOS applications?

My primary focus has been on developing web apps using Angular, but now I am interested in creating native Android and iOS apps with Angular. I have heard about using Cordova, Capacitor, and NativeScript for this purpose, as alternatives to Ionic due to pe ...

javascript utilizing key inputs

Is there a way I can create a function that activates when the "A" key on my keyboard is pressed, sending a signal to nupp('/TS'), and stops sending the signal when the "A" key is released? <html> <head> <script src=\"htt ...

Using JavaScript to create a JSON object within a table

Currently, I am facing a challenge in creating a JSON object from an HTML table using JavaScript. While I can successfully retrieve the values of each cell in JavaScript, the issue lies in organizing and retrieving them as per my requirements. Here is the ...

Leveraging async.js to perform in-depth population in sails.js

Facing a major challenge with my function in sails.js (v12). I am attempting to retrieve all userDetail using async (v2.3) for deep populating my user info: UserController.js: userDetail: function (req, res) { var currentUserID = authToken.getUserID ...

What is the best way to display all divs once more after all filter-checkboxes have been unchecked?

I created a custom filter that displays board games based on the number of players and playing time selected through checkboxes. Initially, the filter works as intended when first loaded and used. However, I encountered an issue where if all checkboxes are ...

Creating PHP output and storing it in a file in a format that is not human-readable

I have received a response from the SOAP client and I am trying to format this output in my PHP code. My goal is to write this formatted output into a file that is readable for users. However, when writing to the file, there are no spaces or new lines in ...

Transferring extra data from jQuery autocomplete to a PHP script

Hey there! I'm wondering if it's possible to pass extra parameters from jQuery autocomplete to a PHP page, which would then use them to query a database and return the results. While I know how to send the typed term from the input box, I'd ...

What could be causing the sluggishness in my jQuery script that checks for required input fields?

My goal is to utilize jQuery to check for required input fields in browsers that do not recognize the required HTML tag. Below is the jQuery script I am using. $('div').on('submit', '#myform', function(e){ e.stopProp ...

`problem encountered when attempting to sanitize HTML through the npm package known as "sanitize-html"`

After researching the documentation, I attempted to use this code snippet: const dirty = '<div>Content</div>'; const clean = sanitizeHtml(dirty); The desired result of 'clean' should be "Content", however it seems that &apo ...

How to create a basic calculator in AngularJS with two textboxes specifically designed for calculating squares?

My code snippet is as follows: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div ng-app="app"> <div ng-controller="Calcu ...

Retrieve Element By Class Name in JavaScript

How can I modify the border color at the bottom of the .arrow_box:after? Javascript Solution document.getElementsByClassName("arrow_box:after")[0].style.borderBottomColor = "blue"; Despite trying this solution, it seems to be ineffective! For a closer ...