Retrieving JSON data from an external file outside the realm of $.getJSON

As I work on converting a 2-character country code to its longer name, it seems logical to me to save this information in an external JSON file rather than embedding it directly into the script. However, while I am able to successfully read the JSON data into an array, I seem to be encountering a scoping issue:

    var countries = {};
    $.getJSON("countrycodes.json", function(data) {
        for (let i in data) 
                countries[data[i].code] = data[i].longname;
        console.log(countries["MX"])     // outputs "Mexico"
    });
    console.log(countries["MX"])         // returns Undefined

The contents of my countrycodes.json file are as follows:

[
    {"code" : "US", "longname" : "United States"},
    {"code" : "CA", "longname" : "Canada"},
    {"code" : "MX", "longname" : "Mexico"},
    {"code" : "RU", "longname" : "Russia"}
]

Answer №1

Attempting to retrieve data from outside of the ajax call is futile due to its asynchronous nature, causing a delay in visibility. As a result, the outer console.log statement will consistently output undefined.

Answer №2

Perhaps the only viable option is to execute the call synchronously? While this approach may not typically be encouraged, I am personally not overly concerned about the slight delay in fetching a small 5 KB text file from our local website:

    var countries = {};
    $.ajax({ url: "countrycodes.json", async: false, dataType: 'json', 
         success: function(data) {
             for (let i in data) 
                     countries[data[i].code] = data[i].longname;
         }
    });
    console.log(countries["MX"])        // Outputs "Mexico"

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

Guide on incorporating file uploads in an Angular 6 project

I am currently working on creating a component where I have implemented a file upload function in a child component and am attempting to use that component's selector in another one. Here is my project structure: - upload : upload.component.html up ...

Stopping the sound when its' Div is hovered over

I've managed to successfully trigger the audio to play on hover, but I'm having trouble getting it to pause when my mouse leaves the area. Check out the code in action here: https://jsfiddle.net/jzhang172/nLm9bxnw/1/ $(document).ready(functio ...

Prior activation of express render before parameter assessment

Seeking guidance as a newcomer to nodejs, express, and javascript. Here is the code I currently have: router.get('/', function(req, res, next) { const content = fileReader(); res.render('index', { "content" : content } ); }); ...

incorporate a new component in real-time

I need help with dynamically adding components to my container in AngularJS. I have a componentA that functions as a container, and I want to add multiple instances of componentB when a button is pressed. Currently, I can successfully add a single instanc ...

Unable to access information through ajax when connecting to mysql database

Having a code that can add, edit, delete and view is good. When all the codes are put together in one file, it works fine. However, wanting to have it separately poses a problem with the "View" part. Despite trying to search for a solution, the functionali ...

Tips for uploading an image to a server using POST ajax

I have a scenario where I am sending an image through $_POST using ajax to my script. When I check the $_POST array, it shows a long string of data that represents the image being sent. array(14) { ["-----------------------------20696645224692318267390959 ...

Can anyone provide guidance on locating the parent of a pseudo element with Selenium WebDriver?

Is there a way to retrieve the parent web element of a pseudo element (if we can call it the parent) using JavaScript? I know that Selenium's methods for searching for web elements are not suitable for pseudo elements, but JavaScript does allow manipu ...

Looking for a simple method to display a popover using conditional if/else statements?

On my website, I am utilizing JavaScript to determine the user's Facebook status. This includes checking if the user is already logged in and has allowed our app, if they are logged in but haven't authorized our application, or if they are not lo ...

How can I include additional lines in a 3D model?

https://i.sstatic.net/NH1sB.png In my latest project using three.js, I created a 3D human model and now I want to enhance it by adding angle lines similar to the red ones I manually drew on the image. Does anyone know how to achieve this effect? ...

Maintain cookie persistence beyond browser shutdown

Using this code snippet in Node-Express JS, I am creating a cookie with a JWT token included. Here is the code: var token = jwt.sign(parsed.data, "token_secret", {expiresIn: "43200m"}); res.setHeader('Set-Cookie', 'token='+token+&apos ...

What might be causing my AJAX success callback function to not function as anticipated?

I've written this code for an ajax request, but I'm struggling to figure out why the code inside the success method isn't functioning properly. Even though the network tab in my Chrome browser shows a state of 200 OK. Here is the ajax code ...

ng-enter animation not working for ui-view nested within another ui-view after page reload

It seems like the issue lies with the ng-enter event not being properly triggered in the lowest level of the ui view hierarchy. I'm unsure how to resolve this problem effectively. In my extensive angularjs application, nested sub-views work flawlessl ...

Ways to expand the play and pause buttons and adjust the height of an HTML audio player

It's clear that the PLAY/PAUSE icons are smaller than intended, and the entire player is thinner than desired, making it difficult for some viewers to see. How can I enlarge the entire player? I have read that we do not have access to individual contr ...

Angular does not select the variable_name within the $scope

Here is the HTML code I have written. <div class="container" ng-app="mintcart"> <div class="panel panel-default" ng-controller="categoriesctrl"> <input type="hidden" ng-model="session.sid" value="<?php echo session_id();?>"/&g ...

Set up a local storage system to store the background color for my page

I have a unique feature on my website where clicking a button generates a random background color each time. However, I am looking to enhance this by implementing a localstorage function that will remember the last clicked color even after closing or reloa ...

Encountering an 'Unexpected token x in JSON at position 1' error while attempting to parse a JSON string embedded within HTML

I've been attempting to convert a hardcoded JSON string into a usable format, but I am struggling to make it work properly. I keep encountering 'Unexpected token' errors or strange outputs. The library I am using is jQuery. The data that nee ...

Using PHP to extract data from a JSON file and store it in a SQL database

I've been researching various methods to parse my file, but none seem to work correctly. I attempted two codes, both of which inserted my data into SQL three times; the first insertion was successful while the subsequent ones were blank. Below are exc ...

Select a particular column (utilizing CSS multi-column functionality)

I want to style the second column in a text block with two columns using CSS or JavaScript. How can I achieve this without creating separate containers for each column? I'm aware that I could create two containers and target the second one for styling ...

Show information once options have been chosen from the dropdown menu in CodeIgniter

As a newcomer to this platform and to codeigniter and Ajax, I'm seeking assistance. I am looking to dynamically display data without reloading the page or using a submit button after selecting an option from a drop-down menu. Although I have successf ...

Struggling with creating a simple AngularJS controller

Apologies if my question seems basic, but I am currently learning about AngularJS controllers. Below is the structure of my project: https://i.sstatic.net/EQOel.png Here is the snippet of my HTML code: <!doctype html> <html ng-app> <hea ...