Is it possible to asynchronously access a JSON object that has been retrieved from a local file on a global scale using the XMLHttpRequest method and

Having some trouble manipulating data from a local JSON file using this technique (no jQuery) as I can't seem to access the object on a global scale:

 var actual_JSON;

 function loadJSON(callback) {   
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'my_data.json', true);
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            callback(xobj.responseText);
          }
      };
    xobj.send(null);  
 }

The function is called after the document loads, using an anonymous function like so:

function loaded(e) {

    loadJSON( function(response) {
            actual_JSON = JSON.parse(response);
            console.log(actual_JSON); // Object {...}
        }
    );
    console.log(actual_JSON); // undefined
};

document.addEventListener("DOMContentLoaded", loaded, false);

I'm struggling with understanding closures and how they impact the scope of actual_JSON. It seems to be limited to the anonymous function within loadJSON(), despite my global declaration.

Answer №1

To better organize the code, consider defining actual_JSON in an outer scope:

function loaded(e) {
    var actual_JSON;
    loadJSON( function(response) {
            actual_JSON = JSON.parse(response);
            console.log(actual_JSON); // Object {...}
        }
    );
    console.log(actual_JSON); // undefined
};

document.addEventListener("DOMContentLoaded", loaded, false);

In this example, the variable actual_JSON was initially defined within the function(response) scope and therefore was not accessible within the loaded(e) scope.

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

When json_decode is called, it will parse a JSON string rather than returning

<?php $json=file_get_contents('php://input',true); $data = json_decode($json, true); print_r($data); ?> Here is the output: {"EventTitle":"Game","EventBody":"body","EventDate":"20 November, 2016","EventType":"party"} The JSON data that ...

Issue: Angular is indicating that the 'feedbackFormDirective' member is implicitly assigned with type 'any'

I am encountering an error in my project while using Angular version 12. Despite extensive research, I have been unable to find a solution. Here is my .ts file: import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Feedba ...

"Maximizing Search Efficiency: PHP Ajax Live Search Supporting Multiple Values

Looking to enhance my Php Ajax Live search functionality by adding a dropdown element for a more refined search. How can I integrate the dropdown value into the existing script? <input type="text" name="value1" id="value1"> <select id="value2" n ...

Displaying AJAX response with AngularJS

My Angular script structure is shown below: var myapp = angular.module("Demo",["ngRoute"]) .config(function($routeProvider){ $routeProvider .when ...

The process of passing parameter values by function in useEffect

Hi everyone, I hope you're all doing well. I'm currently facing an issue with trying to retrieve data from my API using the post method. The problem is that I can't use useEffect in any parameter. So, my workaround is to pass the data throug ...

"Encountering a Python JSON TypeError while attempting to parse data from

I am relatively new to python and stumbled upon an example that almost fits my needs, but I am encountering errors while trying to parse data from a GET request response. The specific error message I keep facing is: "activity['parameters'][& ...

Unfortunately, the datepicker feature does not seem to work properly on elements that have been dynamically added through the

My code progress so far is as follows: $('body').on('change', '.dropdown', function() { $.ajax({ success: function(res) { if(res.success == true) { return elements that have the class ...

Converting JSON data into a JavaScript array and retrieving the array through an AJAX request from PHP

Currently, I am working on a project where I have created a function named AjaxRequest to manage all my AJAX requests. While making the requests is not an issue, receiving and placing the data back onto the page has proven to be quite challenging. Within ...

CodeIgniter does not support the foreach function

I am encountering an issue with the foreach function where the resulting data is not displaying all information from the database. The table in question is named "view_kebutuhan_perjal". Code snippet from Model: function getPerjal() { $query= ...

AngularJS allows users to seamlessly retain any entered form data when redirected, enabling users to pick up right where they left off when returning to the form

I am currently working on a user data collection project that involves filling out multiple forms. Each form has its own dedicated HTML page for personal details, educational details, and more. After entering personal details and clicking next, the data ...

What is the process of turning an SVG element into a clickable link?

Is there a way to transform each element within an SVG image embedded in an HTML file into an active link? I want to create an SVG image with clickable elements. Here is a snippet of the SVG image: <svg version="1.1" id="Layer_1" xmlns="http://www.w3 ...

A guide on incorporating a customized Google map into your website

Recently, I utilized the Google Map editing service from this site: https://developers.google.com/maps/documentation/javascript/styling This link provided me with two things: 1. A JSON code 2. The Google API link However, I am unsure about how to incorpo ...

Issues with JQuery Ajax rendering in browser (suspected)

I'm encountering an issue on my webpage. I have a div with two hidden fields containing values of 0 and 2, respectively. Upon clicking a button that triggers an AJAX query, the div contents are updated with hidden field values of 1 and 2. However, it ...

How to append a JSON object to an existing .json file

UPDATE: Despite successfully executing the PHP code, my JSON file remains unchanged. I must apologize in advance for covering old ground, but I have spent countless hours exploring different solutions with no success. Perhaps sharing my challenge could as ...

Having trouble getting a div to slide to the left on hover and collapse on mouseout using Jquery?

Hey there! I need some assistance in completing this code snippet. I have a div with overflow:hidden and a margin-left of 82px. Inside it, there is a share link and a ul list containing three external links. When I hover over the share link, everything w ...

What is the best method for constructing a JSON object in Flutter?

Here is the data structure that I am trying to send from my Flutter client to the server: { "questions": [ { "question" : "La velocidad de la luz es igual a", "solucion1": "30 ...

Embed a static label inside an input field that remains constant even while text is inputted, without using a placeholder. Crafted using HTML,

Take a look at the screenshot below - what you see on the left side is my current setup, while on the right side is the desired outcome achieved without any plugins or HTML5 attributes The left side scenario occurs when I have 2 input fields - one with th ...

Transmit data from an HTML form to PHP using JSON

I am attempting to utilize JavaScript to send POST data. I have the data in an HTML form: <form name="messageact" action=""> <input name="name" type="text" id="username" size="15" /> <input name="massage" type="text" id="usermsg" si ...

How can JArray be manipulated if the index is subject to change?

I have a JSON file that may contain varying numbers of items in the JSON array. The current code I am using is as follows: var obj = JArray.Parse(File.ReadAllText(url)); dfd = (from a in obj where a["PriceItems"][0]["CityFromID"].Value&l ...

What is preventing me from executing node.js and socket.io within a screen or utilizing Forever?

I'm encountering an issue with running nodejs in a screen. The problem arises when I leave the screen and no sockets are connected. The next person trying to connect will face an error message until the screen is reopened using screen -R node. Once th ...