Utilizing a modular perspective in JavaScript to load JSON files as a view

I've been working on implementing a modular view approach for retrieving data from a JSON file in my JavaScript code, but I'm facing some issues. The snippet of code where I am trying to load the JSON file is contained within a separate JS file and looks like this:

var fileConfigModule = (function () {

  var jsonData = {};

  function initialize() {
    loadJSON(function (json) {
      jsonData = json;
    });
    return jsonData;
  }

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

  return {
    loadJSON: loadJSON,
    init: initialize
  }
})();

I want to utilize this module in my main file to asynchronously load the JSON data using a callback function. Here's how I plan to do it:

var jsonData = fileConfigModule.init(); 

If anyone can offer assistance on what might be going wrong here, I would greatly appreciate it. Thank you!

Answer №1

When you call an asynchronous function but expect a synchronous return value, it can lead to issues in your code.

To resolve this, consider updating your code as shown below:

var fileConfigModule = (function () {

  function initialize(callback) {
    fetchData(function (json) {
      callback(json);
    });
  }

  // The loadJSON function is actually hidden from view

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

  return {
    fetchData: fetchData,
    initialize: initialize
  }
})();

You should then call the function like this:

var arData = null;
fileConfigModule.initialize(function(data){
  arData = data;
}); 

If you're unsure why the loadJSON function is being hidden, consider using it directly instead of calling the initialize function.

By calling fetchData,

var arData = null;
fileConfigModule.fetchData(function(data){
  arData = data;
}); 

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

Using an AngularJS directive to trigger a function with ng-click

Everything is working well with my directive, but I would like to utilize it within ng-click. Unfortunately, the function inside the link is not getting triggered. Here's the link to the code snippet. <div ng-app="editer" ng-controller="myCtrl" ...

What is causing this form to submit?

I need help with sending emails via AJAX. My problem is that the form keeps submitting and refreshing, even though I haven't used GET to send anything in the URL. HTML: <form onsubmit="ajaxEmail(); return false;" > <input type=" ...

Assistance needed in extracting the body content utilizing javascript or jquery

I am looking to swap out the body content of one page with that of another. How can I retrieve the body content from the response text of the second page in order to make this replacement? Please assist me with this. Thank you in advance, Raja ...

Generating a JSON file on the fly using Node.js

I am struggling with dynamically creating a JSON. I have retrieved the data from a sent JSON and the body.value appears as follows: { hubspotProperty: 'question3', response: 'Nous utilisons un google drive mais il est très peu uti ...

Is there a way for me to extract all the elements within an object nested inside an array and then append them to another array?

I'm currently facing a challenge that's bothering me quite a bit. My skills in handling JSON data manipulation are not up to par. The problem I'm dealing with involves an array of multiple objects, each containing some data. Within these ob ...

Swapping out the entire vue.js container

I have a custom vue.js widget that I initialize like so: var myWidget = new Vue({ el: '#widget-container', methods: { loadData:function() { // custom functionality here } }, }); The HTML structure is as f ...

Tips for adding animation to a React state value change triggered by an input

In my React application, I have a form with multiple fields that each contain a text input and a range input. Currently, both inputs share the same state value and onChange function to keep them synchronized. However, I would like to add an animation effe ...

Implement necessary validation for the country code selection on the dropdown menu using the intl-tel-input jQuery plugin

Check out the intl-tel-input plugin here Currently, I am utilizing this plugin and attempting to implement required validation on the country code drop-down. However, the plugin seems to be restricting me from achieving this. I have made several attempts ...

Developing a TypeScript library through modular class implementation

I have developed a Web API and now I want to streamline my code by creating a library that can be reused in any new project I create that interacts with this API. My goal is to organize my code efficiently, so I plan to have separate classes for each endp ...

In need of assistance with posting data on a Captive Portal using Ruckus AccessPoint Javascript

We are currently working on implementing a captive portal using Ruckus AP for our guests. Our setup includes a form where users can input their username and password. Upon clicking "Login", we aim to post this data to the Ruckus AP's user_login_auth. ...

Obtain $stateParams excluding UI-navigation

Is there a way to access $stateParams without using a <ui-view> tag in the HTML? I'm trying to make this code function properly: .config([ '$locationProvider', '$stateProvider', function($locationProvider, $stateProvide ...

How to add data to Laravel after successful ajax request

I have a div containing bids: @foreach($bids as $b) <div class="bids notice notice-lg"> <strong>{{$b->user->name}}</strong> is offering <span style="font-size: 18px" class="label label-success">{{$b->bid}} €</span ...

The AngularJS $rootscope $destroy event is not being triggered, resulting in timeouts not being cancelled

Below is the code snippet that I am currently working with: function initialize() { var defer = $q.defer(); var deferTimer = $q.defer(); var cancelTimeout = $timeout(function() { if (defer !== null) { ctrlr.setProcessingParameters('X ...

v-autocomplete not displaying full list of items in selection dropdown

I have a question regarding sending an array with values ranging from 1 to 100 on the v-autocomplete item props. However, when scrolling through the list, only numbers up to 40-50 are visible. <template> <v-app> <v-container> ...

Unable to showcase information in the center of an HTML document

Hello, I'm facing an issue with my HTML page that has a left vertical nav-bar. Despite my efforts, I can't seem to display content (text) in the center of the page as shown in the screenshot with the red oval. I've attempted inserting text ...

React is throwing a parsing error due to the incorrect use of braces. Remember, JSX elements must be wrapped in an enclosing tag. If you were trying to include multiple elements without a parent tag, you can use a JSX fragment

Having recently started working with React, I came across this code snippet return ( <div> dropdown ? (<li className='goal-list-item' onClick={() => setDropdown(!dropdown)}>{goal.name}</li>) : ...

JavaScript's asynchronous callbacks

As a PHP developer delving into the world of NodeJS, I find myself struggling to fully grasp the concept of asynchrony in JavaScript/Node. Consider this example with ExpressJS: router.get('/:id', function (req, res, next) { var id = req.par ...

Formatting dates in the Bootstrap Date Picker within Angular 6

When using Angular 6, I incorporate a date picker by adding the bsDaterangepicker class for selecting a date range. <input type="text" (ngModelChange)="dateFilterChanged($event)" [(ngModel)]="myDateField" value="{{ myDateField | date:'yyyy-MM-dd&a ...

The Ajax request functions flawlessly on Mozilla but encounters issues on Chrome, causing confusion as it occasionally works

I am using a PHP file with a class and function to store data in the database, accessed via AJAX. While everything works smoothly in Mozilla, Chrome seems to be causing some issues. Strangely, sometimes it works fine, but other times it fails for no appare ...

I'm attempting to store the information from fs into a variable, but I'm consistently receiving undefined as the output

I'm currently attempting to save the data that is read by fs into a variable. However, the output I am receiving is undefined. const fs = require("fs"); var storage; fs.readFile("analogData.txt", "utf8", (err, data) =&g ...