Is there a way to construct a Javascript function, without relying on JQuery, for fetching JSON objects from varying

I have been searching for a non-JQuery AJAX function that can fetch data from a URL and return it as a JSON object.

For example, let's say I want to display information about Users from one JSON located at URL1 and also include information about Posts from another JSON located at URL2 in the same display.

I would like to achieve this without using JQuery.

Here is an example of how I envision this:


function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
    if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
            if (success)
                success(JSON.parse(xhr.responseText));

        } else {
            if (error)
                error(xhr);
        }
    }
};
xhr.open("GET", path, true);
xhr.send();
}

function getInfo(){
var users, posts;
loadJSON('http://.com/users',
         function(dataU) {
            users = dataU;
         },
         function(xhr) { console.error(xhr); }
);
loadJSON('http://.com/posts',
         function(dataP) {
            posts = dataP;
         },
         function(xhr) { console.error(xhr); }
);

console.log(users);
console.log(posts);

}

getInfo();

Answer №1

If you prefer not to use jQuery, you can utilize plain JavaScript XMLHttpRequests instead. This method will enable you to establish an HTTP connection with a remote server and retrieve data using methods like GET.

To start making these requests, you can refer to MDN's introductory guide.

The JSON.parse() function is useful for converting JSON strings into JavaScript objects.


For an alternative approach to using XMLHttpRequests, consider exploring the fetch API. It offers a more streamlined interface for handling HTTP requests. Keep in mind that it is still experimental, so you may need to use a polyfill for broader browser support.

Answer №2

Regardless of whether you're using jQuery, the XMLHttpRequest object operates asynchronously. jQuery actually utilizes it internally. Just so you know, AJAX stands for Asynchronous Javascript And Xml (AJAX). This implies that you can't expect a synchronous outcome from an asynchronous function. However, you can and should handle the result within a callback function that is passed to the request.
The proper technique involves calling console.log (or any other desired action) from the success or error callbacks.
There are established methods for gracefully degrading when the XMLHttpRequest feature isn't accessible. These include creating and appending script or iframe elements, then retrieving data from their .onload handlers. It's worth noting that all of these techniques operate asynchronously, and the same principles mentioned above still hold true for them.
Remember: You Cannot Receive Synchronous Result From Asynchronous Function.
I stand by this statement despite any potential criticism.

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

Tips for implementing bslib package pop up window within a table displayed using rhandsontable in R Shiny

I am trying to implement the template from Laurent's answer on R Shiny - Popup window when hovering over icon in my code below, which involves integrating a popup window into a rhandsontable table. My goal is to display the popup window as depicted in ...

Error: Undefined Function [Thinkster.io's Angular Tutorial Chapter 4]

Currently working on the Angular Tutorial provided by Thinkster.io and enjoying every bit of it. However, I've hit a roadblock in Chapter 4 that seems impossible to overcome. Whenever I attempt to execute a Post or Delete action, I encounter the follo ...

Tips for making a 2D grid on a webpage

Is there a way to implement a 10x10 grid on a webpage where users can click anywhere on the grid and have their (x, y) position recorded with one decimal place accuracy, covering values between 0.0-10.0 or 0.1-9.9? Appreciate any guidance! ...

Maintaining the proportions of images in different screen sizes when resizing

I apologize if this question has already been addressed, but I have been unable to find a solution that works for my specific issue. My Gallery consists of a side list of available images in one section, which when clicked changes the image source in anot ...

Is it feasible to utilize the translate function twice on a single element?

Using Javascript, I successfully translated a circle from the center of the canvas to the upper left. Now, my aim is to create a function that randomly selects coordinates within the canvas and translates the object accordingly. However, I'm encounter ...

What is the best way to arrange elements based on the numeric value of a data attribute?

Is there a way to arrange elements with the attribute data-percentage in ascending order, with the lowest value first, using JavaScript or jQuery? HTML: <div class="testWrapper"> <div class="test" data-percentage="30&qu ...

Triggering a click event on various instances of a similar element type using the onclick function

Hey there, I'm a newcomer to Javascript. I've been practicing my Javascript skills and trying to replicate something similar to what was achieved in this example: Change Button color onClick My goal is to have this functionality work for multip ...

The function Expo.Fingerprint.isEnrolledAsync will provide an output that includes information about fingerprint

Attempting to incorporate fingerprint authentication into my react native app. Utilized Expo SDK for this purpose. Although the Expo.Fingerprint.authenticateAsync() method claims to return a boolean, it actually returns an object when examined closely. E ...

Utilizing Node Js and Socket.Io to develop a cutting-edge bot

Is it possible to run JavaScript with Node.js without launching Google Chrome from various proxies? Can someone provide a sample code for this task? For example, you can find a similar project here: https://github.com/huytd/agar.io-clone Another project c ...

Eliminate the need to input the complete URL every time when making server calls

Currently, my springbok application has a React-Typescript frontend that is functioning well. I am using the request-promise library to make requests like this: get('http://localhost:8080/api/items/allItems', {json: true}). However, I would like ...

Vue: Simple ways to retrieve state data in MutationAction

I'm having trouble accessing the state inside @MutationAction Here is the setup I am using: Nuxt.js v2.13.3 "vuex-module-decorators": "^0.17.0" import { Module, VuexModule, MutationAction } from 'vuex-module-decorators' ...

Retrieve JSON information from within the Scope

In my JSON data, I have the following values: {"minmax":["0.01","67.00"]} I am trying to retrieve this data using jQuery in the following way: $.getJSON("../../dados/opcoesMinMax.json", function(data) { var getM ...

What is the total amount within a specified date range when retrieved as JSON?

Consider the following JSON structure: { "timesheets": [ { "user": { "username": "erik", "first_name": "Erik", }, &q ...

Lost in a strange predicament

As I try to send props from my parent component to the child component, I am facing an issue where one of the children within the coin prop seems to be lost when I receive the props in componentWillReceiveProps(). This discrepancy becomes evident through t ...

Pattern matching in JavaScript using regular expressions is used to identify and extract repeating patterns,

There is a specific string that contains structured data and multiple instances of @doc { within it. I need to extract these occurrences, making sure the result includes two unique matches. To achieve this, regular expressions come in handy: var matches = ...

What is the best way to showcase a half star rating in my custom angular star rating example?

component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { projectRating ...

A step-by-step guide on how to use the Google Closure Compiler: a

Is there anyone who could assist me in adding a snippet to the basic process of Google Closure Compiler? I have been trying unsuccessfully to do this via JavaScript code. I am using an example snippet from the official npm page, but when I run it, someth ...

Two events can be triggered with just one button press

Is there a way to trigger two functions with just one button click? I want the button to execute the check() function and open a popup window with a PHP script. I've tried different approaches but none have been successful. Can anyone assist me? < ...

When a specific condition is fulfilled, I must retrieve a random response from a designated array

I'm looking for a way to create a system where users can select multiple items and then generate a random answer from those selected options. Currently, I have a setup that requires manual input of options in a comma-separated format, but I want to st ...

What could be the reason my mat-form-field is not displaying the label?

I'm currently working on a project using Angular Material to build a web page. I am facing an issue with the mat-form-field component as the label is not displaying, and I can't figure out why. Any assistance would be greatly appreciated. Thank y ...