Using AJAX to retrieve JSON information

Looking for advice on improving my script to fetch JSON data from a server file using AJAX. I am struggling with organizing it into a functional structure.

Below is the current implementation:

function getJSON (file) {
    var request = AjaxRequest();
    var json = "";
    request.onreadystatechange = function () {
        if(request.readyState == 4 && request.status == 200) {
            json = JSON.parse(request.responseText);
        }
    }
    request.open("GET", file, false);
    request.send();
    return json;
}

Although the function meets my requirements, I have received feedback advising against passing 'false' as an argument in the AJAX request due to potential blocking issues. This leaves me unsure about the correctness of my approach. Any suggestions on how I can improve this function? Should I make any changes, and if so, what modifications would be appropriate?

Answer №1

The return process cannot happen immediately in this case because it is an asynchronous operation. Your

json = JSON.parse(request.responseText)
will only occur later once the server responds with data, which may be long after the return statement has already executed. To address this, you can modify your function to accept a callback that handles the returned data:

function getJSON (file, callback)
{
  var request = AjaxRequest();
  request.onreadystatechange = function ()
  {
     if(request.readyState==4 && request.status==200)
     {
       callback(JSON.parse(request.responseText));
     }
  }
  request.open("GET", file, false);
  request.send();
}

To implement this change, you would call the function like so:

getJSON("something.json", function(data) { 
  //utilize the received data, your json object/data
});

In this manner, you are effectively utilizing the data as soon as it becomes available and passing it along to subsequent functions, aligning with the intended behavior of asynchronous calls.

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

The jQuery ajaxError() function triggers if the user navigates away from the page before it has fully loaded

We have implemented a global ajaxError() handler using jQuery to notify users of any AJAX failures: $(document).ajaxError(function() { $("There was a network or server error. Please try again later.").dialog({ title: "Error", mod ...

Tips for customizing Material-UI Switch button appearance

Is there a way to remove the box-shadow on the thumb of the Switch button when it's disabled? I've tried various methods like adding the box-shadow in the switchBase and removing it from the thumb, but it affects the parent element as well. Anoth ...

When handling a document click event in Typescript, an error may occur where it cannot read

Just starting out with Typescript and diving into Angular, I am currently in the process of converting my project to the Angular system. However, I've hit a roadblock. I need to figure out how to close the dropdown content when the user clicks anywher ...

Leveraging $http and $q in an Angular configuration with a service/provider

My goal is to load specific configurations for each controller in the app.config section. Each controller requires a distinct set of data, but these sets are not mutually exclusive. I am struggling to find a solution to this issue. .config(['$routePr ...

What is the process for assigning a value to the body in a div element?

Within a div, there is a body element structured like this: <div id = "TextBox1"> <iframe id = "TextBox1_1"> #document <html> <head></head> <body></body> </html> </iframe> </div> I have attempte ...

After reaching a total of 20 entries, req.body will automatically convert the array into an

I have the ability to dynamically add properties to my form: <form action=""> <div class="property"> <label>Name : <input type="text" name="properties[1][name]"></label> <label>Order : <input type="text" na ...

What is the best method for calculating the total of a mongoose attribute?

I am attempting to calculate the sum of schema using reduce. However, the current code is not adding the items together but rather placing them next to each other. For example, 20 + 30 should result in 50, but instead it gives me 02030. Is there an issue w ...

Displaying extra dropdown menus when a specific option is chosen within a pop-up using JQM

Currently, I have a popup that displays a dropdown list with options 1 to 4. Upon selecting an option from this dropdown, I would like to use an ajax call to show additional dropdown lists inside the popup window. I have created 4 divs for each of the sel ...

Implement JQuery to include a screensaver on your website

My website in asp.net c# displays the performance of a specific process on an LCD TV screen. The data is refreshed every 15 seconds using the code below: <div id="InfoTop"> <table width="100%" cellpadding="0" cellspacing="0"> ...

What is the process by which Node can access predefined variables in clustering?

Consider the following code snippet: var running = false; var cluster = require('cluster'); if(cluster.isMaster){ cluster.fork(); running = true; } If this code is executed within multiple forks, would the value of 'running' ...

Sending files through ajax with php

Hey there! I've been working on uploading files using Ajax and PHP, following a tutorial. Here's the code I have so far: upload.js: var handleUpload = function (event){ event.preventDefault(); event.stopPropagation(); var fileInput= document.ge ...

Changing the style.backgroundImage property overrides any image transition effects

I am currently working on creating a button for a player. You can check out the video (here) The button works, but in order to give it a "pressed" effect, I have to change its background-image on click. However, this action seems to override the transitio ...

Exploring the Validation of POST Requests with JSON Content

When working with NodeJS and Express 4, I often come across situations where the client sends JSON data that needs to be processed: { "data" : "xx" "nested" : { field1: "111", field2: "222" } } However, on the server side, I ...

Changing a JSON object into a collection of string arrays using jq

I have a JSON object that consists of strings and nested objects: { "key1": "value1", "key2": "value2", "key3": { "subKey1":"value3", "subKey2":"value4" } } My goal is to flatten the structure and convert it into an array of strings [ ...

Executing ForceAtlas2 algorithm from a predetermined starting point within Sigma.js

I need assistance with rendering a complex network using the React-Sigma wrapper. The base structure of this network consists of numerous nodes of degree one and some nodes with high degrees. I have prepared my graph data with x and y coordinates that repr ...

Setting attributes on an AngularJS Directive element in real time

My goal is to create a directive in AngularJS with a template that can contain other AngularJS directives. All of my directives require an "id" attribute, so I must set the "id" on the directive within the template. However, no matter how I attempt this, A ...

When I move to a different page, Javascript ceases to function

Currently, I am in the process of creating a user interface with the use of html, css, and javascript. One of the features in my project is an "Exit" menu item that triggers window.close(); when clicked to close the user interface. Strangely, this functio ...

Preventing Ng-repeat from refreshing after deleting using $http request

Once I remove an item from my list, the deleted object's data disappears, but the placeholder (empty row) lingers. (I tried using apply() with no luck) I have a standard CRUD interface displaying expenses. <table class="table table-striped"> ...

The AngularJS framework does not support the Twitter Collection Grid feature

I'm currently facing an issue with implementing a Twitter Collection Grid on my website using an angularJS directive. The grid is not displaying correctly, as the pictures are stacking on top of each other instead of forming a grid layout. I've t ...

Tracking tool for monitoring progress of HTTP POST requests

Hi, I am still a beginner when it comes to NodeJS and its modules. I could really use some assistance with creating a progress bar for an application I'm working on. Right now, the progress bar only reaches 100% upon completion and I suspect my piping ...