Error occurs in console when using .getJSON with undefined JSON, but does not happen when using embedded data

Can someone help me understand why I'm getting an 'undefined' response when I use console.log(tooltipValues), but there's no issue with console.log(tooltipJSON).

I've noticed that when I embed the data directly in my JS code, everything works fine. However, exporting the data to a JSON file causes it to break. I need to avoid embedding JSON due to the large number of records it will eventually hold.

var tooltipJSON;
    $.getJSON("js/tooltips.json", function(data) {
      tooltipJSON = data;

      $('.skill, .trinket, .hero').hover(
        function() {
          var tooltipValues = tooltipJSON[$(this).data("tooltip")];    
          console.log(tooltipValues);
          console.log(tooltipJSON);

          if(!tooltipValues)return;
          var tooltip = $("<div class='tp-popup'><div>" + tooltipValues.value1 + "</div><div>" + tooltipValues.value2 + "</div></div>")
            .css({
              'color': '#fff',
              'position': 'absolute',
              'zIndex': '99999',
              'width': '100px',
              'height': '150px',
              'background-color': '#333',
            });
          $(this).append(tooltip);
          $(document).on('mousemove', function(e) {
            $('.tp-popup').css({
              left: e.pageX,
              top: e.pageY
            });
          });
        },
        function() {
          $('.tp-popup').remove();
        }
      );
    });

However, the following internally embedded JSON works without any issues:


tooltipJSON = {
    "skill-one": {
      "value1": "skill-one value1",
      "value2": "skill-one value2",
      "value3": "skill-one value3"
    },
    "trinket-two": {
      "value1": "trinket-two value1",
      "value2": "trinket-two value2",
      "value3": "trinket-two value3"
    }
}
$('.skill, .trinket, .hero').hover(
        function() {
          var tooltipValues = tooltipJSON[$(this).data("tooltip")];    
          console.log(tooltipValues);
          console.log(tooltipJSON);

          if(!tooltipValues)return;
          var tooltip = $("<div class='tp-popup'><div>" + tooltipValues.value1 + "</div><div>" + tooltipValues.value2 + "</div></div>")
            .css({
              'color': '#fff',
              'position': 'absolute',
              'zIndex': '99999',
              'width': '100px',
              'height': '150px',
              'background-color': '#333'
            });
          $(this).append(tooltip);
          $(document).on('mousemove', function(e) {
            $('.tp-popup').css({
              left: e.pageX,
              top: e.pageY
            });
          });
        },
        function() {
          $('.tp-popup').remove();
        }
      ); 

The main problem seems to be related to the utilization of external JSON data. The line console.log(tooltipValues) acts up when using external JSON files, even though the main console log of the JSON itself functions perfectly. Both logs work as expected when dealing with internal embedded JSON.


$('.skill, .trinket, .hero').hover(
        function() {
          var tooltipValues = tooltipJSON[$(this).data("tooltip")]; 
          console.log(tooltipValues);
          console.log(tooltipJSON);
        

Answer №1

When working with JQuery's getJSON method, it is important to note that it behaves differently across various versions of JQuery. As such, errors may occur silently if the fail callback is not implemented. If your JSON content has a trailing comma before the end, it could cause the method to fail. In my case, using JQuery version 2.1 did not display anything until I upgraded to version 3.1.1 and identified and fixed the issue. Below is a snippet of the code I used for testing:

var tooltipJSON;
$.getJSON("js/tooltips.json", function (data) {
  tooltipJSON = data;
  console.log("data", data);
  var key = $(this).data("tooltip"), tooltipValues = tooltipJSON[key];
  console.log("'"+key+"'", tooltipValues);
}).fail(function (err) {
  console.log("error", err);
});

It is important to ensure that the external JSON file is structured as an object {...}, rather than an array containing an object [{...}]:

{
  "skill-one": {
    "value1": "skill-one value1",
    "value2": "skill-one value2",
    "value3": "skill-one value3"
  },
  "trinket-two": {
    "value1": "trinket-two value1",
    "value2": "trinket-two value2",
    "value3": "trinket-two value3"
  }
}

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

Tips for retrieving the value of a corresponding data attribute by the text within a div using jQuery in JavaScript

I have several divs with different names and values assigned to the data attribute data-category Now, I am in need of retrieving the value of data-category based on specific text present inside the div. <div class='ext-category' data-categor ...

How can I convert an integer to a string within a Laravel JSON object?

After upgrading my server to a more recent version of MySQL and PHP 7, I noticed a change in the way Laravel's response()->json() function handles tinyint data types. Previously, on PHP 5.5, it would always convert them into strings. However, with ...

Trigger a function when <a> is clicked, which will then increment the count by one and reflect this change in the database

The database generates the content of this div ordered by a count number called "cts". Whenever I click on the div, I want the "cts" number to increase by one, and then update the change in the database. This will result in the content changing accordingly ...

Tips for clearing all content within a React Material UI table

How can I create a reset button to clear a table filled with user input data, without having to write functions from scratch? For example, similar to using clearLayer() for clearing a leaflet map. Thank you for any suggestions! //example of dynamical ...

Exploring ways to incorporate mouse movements into this simple JavaScript script

I have recently decided to convert my JavaScript code into jQuery code to incorporate mouse events. After downloading the latest version of jQuery and renaming it as "jquery.js," I made modifications to my manifest.json file by adding "jquery.js." However, ...

The specified URL is not compatible with Json

As a new programmer, I am in the process of building an app using JSON. I have encountered an issue where one URL doesn't work: . However, when I use this other URL, my app works perfectly: . It's worth noting that both JSON files are exactly the ...

Outdated JavaScript Alert

Is it possible to use JavaScript to create an alert message in my input field when a past date is selected? I would like the warning to say "past date, please enter a valid date." <html lang="en"> <head> <meta charset="U ...

Displaying one out of two elements when the button is clicked

Trying to implement two buttons on the parent component, each displaying a different component - one for itemlist and the other for itemlist2. Struggling to get it right, even after following an example at https://codepen.io/PiotrBerebecki/pen/yaVaLK. No ...

Issue with form action redirection on Node JS Express server not functioning correctly

My EJS application involves using jQuery in the JavaScript code to fetch JSON data from the Google Custom Search API. The app then uses the GET method to navigate to /search, passing the query as the attribute for q. Here's an example of the form&apos ...

Bootstrap alert JS refuses to slide down

Here is the JavaScript code to make a blue bar slide down on click: $('#comment').click(function(e) { e.preventDefault(); $('#comment').slideDown(); }); ...

Error encountered while returning JSON from a RESTful API in Quarkus due to LazyInitializationException

I'm currently working on developing a straightforward Quarkus application. My project involves two entity classes that have a one-to-many relationship: @Entity public class Person extends PanacheEntity { public String name; public LocalDate ...

Filter the object by its unique identifier and locate the entry with the highest score

I'm currently working on figuring out the proper syntax for sorting an object by ID and then identifying the highest score within that ID array. While I've managed to sort the object up to this point using conditionals and the sort() method, I&ap ...

What is the best way to remove a specific HTML section using a JavaScript function?

I am struggling to figure out how to remove a specific HTML section using a button that is contained within the section itself. The section I want to delete was initially added by clicking a different button. Although I can successfully add a new section ...

Is it possible for me to retrieve/load a <datalist> element from a different file?

I'm in the process of developing a Google Chrome extension that essentially consists of a dropdown menu and an input box with datalists. The user can change their selection in the dropdown menu, which will then switch the datalist being used by the in ...

The process of generating collection names dynamically based on user information

My goal is to enhance the structure of my data collection and make it more organized. While I am familiar with accessing and retrieving data, I am unsure about creating the schema. Here is my current schema: var MySchema = new Schema ({ event: { ...

Modifying dynamic input fields based on the selected input field type

Seeking advice on a challenge I'm facing while testing a website. My task is to mask input fields in screenshots after executing tests because we share data with other teams. I've tried using JS before the script by changing the input type to &ap ...

The issue arises when attempting to update the input of a child component within a reactive form during the OnInit lifecycle

My dilemma arises in working with data stored in the ngrx entity store, as it gets displayed in chunks based on pagination. The issue lies with rxjs somehow remembering the paging history. For instance, when I fetch the first page of data from the server, ...

Issue with video.js text track memory leakage (WebVTT/VTT)

I am utilizing Video Text Tracks to showcase advanced live information on top of the video. A new video is loaded every few minutes, each with its own .webvtt file (consisting of 2-3k lines). Although everything is functioning properly, there is a persis ...

Stop the default behavior of a link based on the Ajax response

A controller has been created in Magento to check if there are any products in a list. If products exist in the list, it will return true; otherwise, it will return false. The front-end below triggers an ajax call. It must remain a link and cannot be chan ...

URL Labeler StateProvider: A unique StateProvider that adds a distinctive label to the

I need help figuring out how to add a user-friendly URL at the end of the current URL using $stateProvider. As an example, on StackOverflow's question pages, the URL format is stackoverflow.com/questions/(question_id)/(question title). I want to repl ...