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

I found myself pondering the significance of the {blogs: blogs} in my code

app.get("/articles", function(req, res){ Article.find({}, function(err, articles){ if(err){ console.log("an error occurred!!!"); }else{ res.render("homepage", `{articles: articles}`); } }); I created this c ...

Sending a file through an Ajax POST request to a PHP server

I am attempting to upload the HTML input file to my PHP file using a different method than the traditional synchronous HTML forms. The problem I am encountering is that it seems like I am not correctly POST'ing the input file to my PHP file because t ...

Button click causing TextField to print incorrectly

I am working on implementing a feature in my react application where users can input a search term, and upon pressing the button, it will be used to perform a search. The text input field and button are utilizing material-ui components. At this stage, I si ...

Having trouble with my sorting algorithm - am I overlooking something obvious?

function Controller($scope) { var sortItems = [ { "text": "Second", "a": 2 }, { "text": "Fifth", "a": 5 }, { "text": "First", "a": 1 }, { "text": "Fourth", "a": 4 }, { "text": "Third", "a": 3 } ]; va ...

How can you make a Dropdown Box with Javascript?

My current table setup is as follows: <table> <tbody> <tr> <td>List 1</td> <td>List 2</td> <td>List 3</td> <td>....</td> </tr> <tr> <td>This section would be the dropdown ...

Using an element with the href property in conjunction with react-router: a comprehensive guide

My goal is to implement the navigation.push(url) functionality upon clicking an anchor tag element in order to prevent the app from refreshing when navigating to a new page, thus allowing me to maintain the application state. The decision to use this on a ...

JavaScript Datepicker Formatting

I need to modify the date format of a datepicker. Currently, it displays dates in MM/DD/YYYY format but I want them to be in DD-MM-YYYY format. <input id="single-date-picker" type="text" class="form-control"> Here's the JavaScript code: $("# ...

Pre-rendering Vue.js for SEO with prerender-spa-plugin becomes unresponsive during the npm run build process

My current issue arises when attempting to execute the command npm run build while utilizing the pre-rendering plugin in my webpack configuration. I incorporated some advanced options in webpack such as: `captureAfterDocumentEvent: 'fetch-done' ...

Struggling to retrieve values from a JSON class in C#?

After taking on the challenge of using the Twitch JSON API without prior experience, I decided to use json2csharp.com to convert a JSON string into a class structure. Here is what it looks like: class TwitchAPI { public class Preview { pub ...

Converting a JSON object into an array of objects for Retrofit deserialization

Currently, I am facing an issue with deserializing the response from an external API in my Android app that uses Retrofit. The JSON format of the response is as follows: { "attribute_1": "value", "attribute_2": "value", "member_1": { " ...

The issue of mapping C# optional parameters with JSON data in an Ajax request, specifically when they have the same name but different types

Having trouble with the json data Parameters of an ajax request not matching properly for an optional parameter of a c# method $.ajax({ url: '/CusotmerManagement/Cusotmer/GetCusotmerByDisplayId/', ...

Navigating through arrays to access nested objects

Currently, I am attempting to retrieve a specific field within a nested array using the following code: var array1 = []; const data = { [userId]: [{ id: id, name: fullName, email: userEmail }, ], ...

Exploring nested JSON arrays with jquery to retrieve information

My current challenge lies in accessing specific values within a nested array. Here is the structure of the array: [{ "call_sign": "KTAB-TV", "facility_id": "59988", "operator": "Nexstar Media Group Inc", "programming_class": [{ "pr ...

Cannot render <Image> inside <Section> component

As a beginner in React, I am attempting to create an app following a tutorial. In my component, I utilized the figure tag but it's not showing up when inspecting element in Chrome. Here are the code snippets: The tutorial includes a div tag as a chil ...

Specialized express Validator for 2 particular fields

I currently have 2 custom validators set up for the fields email and phone. check('phone') .not() .isEmpty() .withMessage('Phone should not be empty') .custom(async phone => { const phoneCheck = await ...

Tips for accelerating the loading of data retrieved through ajax requests

At present, data is being fetched in array form from a PHP script. I have noticed that when retrieving 40 sets of data, it takes approximately 20 seconds for the data to load. This delay may be due to ajax having to wait until all the results are gathered. ...

There was a syntax error in sign.php on line 15 that read: "Parse error: syntax error, unexpected 'if' (T_IF)"

Encountered an issue: Parse error: syntax error, unexpected '$username' (T_VARIABLE) in /home/rainlikq/public_html/script/signupt.php on line 17 when trying to use the username statement.... Looking for suggestions on how to resolve this. Th ...

Can a for loop be implemented within a mongoose schema method?

Is there a way to modify this for loop so that it runs through the entire array instead of adding one by one? Any suggestions? EndorsedSkillSchema.methods = { async userEndorsedSkill(arr) { for (var i = 0; i < arr.length; i++) { const skil ...

The Angular component is failing to display the template

After following a tutorial on UI-Router () I have implemented the following states in my Angular application: angular .module('appRoutes', ["ui.router"]) .config(['$stateProvider', '$urlRouterProvider', function($sta ...

How can we unpack JSON data and retrieve the value in C#?

I am currently working on a Xamarin App project and successfully retrieving Json data from the server. However, I am now facing an issue with reading/viewing the value of "invitation". Json Value: {"invitation":"http://example.co ...