Retrieve the response text using native JavaScript

Dealing with the nature of asynchronous XMLHTTPRequest in JavaScript can be tricky. I faced a challenge where I needed to return the responseText value but found it impossible due to this nature. To overcome this, I came up with a workaround by calling a function that pastes the responseText into a specified ID. However, the issue resurfaced when I needed to retrieve a JSON file and return its value. I attempted to inject responseText into a variable, but it didn't work. I also tried creating an "interface-like" file to handle this task, but to no avail. Are there any known workarounds for this problem?

function httpGetJson( file, type) {
        self.httpState(true);
        try{
            var type = type || true;
            var http = self.http();
            http.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200){
                    returnJson(this.responseText);
                }
            }
            http.open("GET", "json/" + file, type);
            http.send();
        }catch (err){
            return log.error("http.httpGetJson", err.message);
        }
        self.httpState(false);
    }

Check it out on codepen http://codepen.io/mecostav/pen/JNdovR

Answer №1

A callback or a Promise should be added to your function. For instance, the function can receive a function as a parameter

function httpGetJson(file, type, cb) {
    self.httpState(true);
    try{
        var type = type || true;
        var http = self.http();
        http.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200){
                cb(this.responseText);
            }
        }
        http.open("GET", "json/" + file, type);
        http.send();
    }catch (err){
        return log.error("http.httpGetJson", err.message);
    }
    self.httpState(false);
}

Then, the function can be called like this:

httpGetJson('foo', 'bar', function (result) {
    // do something with result
});

Instead of:

var result = httpGetJson('foo', 'bar');
// do something with result

Using the latter approach will not work with JavaScript, so it's best not to attempt to do so. If you really require synchronous http requests, there is a deprecated method for that, which you can search for online (but it's not recommended).

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

What is the best way to substitute </br> and <br/> with in a text?

Is there a way to replace </br> and <br/> with \n functionally? There seems to be varied responses to this query. Errors are often made when writing the break tag. The solutions for both types of breaks mentioned above are detailed below ...

Retrieving XML Information from a Textual Source

When I upload a file of XML type, it generates an input stream. In order to obtain the XML data in the code behind, I convert the input stream into a string using the following: StreamReader stream = new StreamReader(Request.InputStream); string x = str ...

Exploring PostgreSQL's dynamic querying capabilities for JSON data

Extracting details from a JSON value in a PostgreSQL Database has been challenging. The data structure looks like the following: [{"monday":{"opens":730,"closes":2300}},{"tuesday":{"opens":730,"closes& ...

When attempting to render 2 components based on the results of 2 fetch calls using Promise.allSettled(), I encounter difficulties if one of them throws an error

I have encountered an issue while using Promise.allSettled() in sending two fetch calls. I am rendering components based on the result - a component with data if it is fulfilled and an error component if rejected. However, when one of the fetch calls throw ...

NPM - Include in package.json without installation

Can a command be executed to validate that the package is a legitimate npm package, include it as a dependency in package.json, but refrain from actually installing it? This question arises from the need to utilize a specific package globally and incorpor ...

Tips for executing parallax designs, similar to the techniques used on the

Currently, I am in the process of creating a website that utilizes parallax scrolling. Here is a brief overview of what I have accomplished thus far. I decided to use the skrollr plugin to achieve the desired parallax effect. Through this plugin, I was abl ...

Tips for redirecting users after a successful Ajax call

I am currently utilizing twitter bootstrap for my project and have a birthday Modal that prompts users to input their date of birth. The validation and data insertion into the database are functioning correctly, but I am facing an issue with redirecting th ...

Guide on efficiently injecting data into a database using JavaScript and SQL from an array of objects

Let's simplify this process. I am creating a dynamic form for clients to submit data to a PostgreSQL database using React on the front end and NodeJs on the back end. Once the form is filled out, the inputs are stored in an array of objects like this ...

Leveraging HTML and PHP for integrating date and mobile number functionalities

I am a beginner in HTML and PHP. I have encountered an issue where the data displayed shows as "0000-00-00" for dates and if the mobile number entered is less than 9 characters, it displays the same numbers repeatedly. However, when I enter 10 digits for t ...

The jQuery validation feature is failing to function properly within a bootstrap modal

I'm facing an issue with the jQuery validation plugin in my express app sign-up form that uses Bootstrap for the front-end. Despite setting rules and messages for name, email, and phone number fields, the validation is not functioning correctly. Below ...

Using WCF REST to send a JSON payload

Little did I expect that what started as a "quick one hour" project would lead me to posting a question on Stackoverflow two days later. But here we are... I currently have multiple external client applications (java, perl, php, c#) making GET requests to ...

Initiate an ajax call only when new data needs to be fetched for the initial load

I have a question regarding my use of Ext JS. I have been working with this framework for quite some time and am facing an issue that I can't seem to resolve. My application has a tree structure with nodes, and when a node is clicked, a corresponding ...

Implementing click events to control GSAP animations in Next.js

I'm having trouble figuring out how to pause/start an animation using GSAP in Nextjs. Specifically, I can't seem to work with a tl.current outside the useEffect hook within this component. My goal is that when I click on the first .imgWrapper ele ...

Sharing the logger object in NodeJS projects: What's the best approach?

After setting up a logger object in the file utils/logger.js using the winston package, I am wondering how to propagate this logger object to all project files (approximately 20 in total). Do I need to include const logger = require('../utils/logger&a ...

Trouble with linkage in jQuery for AJAX requests in an external .js document

My asp.net application has a master file that includes the jquery.js file. On another page that uses this master page, I have my own jquery code. I attempted to move this code to an external file and then include it in my .aspx file. While most functions ...

Distributing JWT to the recipient using Express

Allow me to provide you with an overview of my application, which is quite straightforward. The main concept revolves around a user inputting their accountname and password into an html form on the /Login page like so: <form action="/Login" m ...

What is the most efficient way to align a localStorage variable with its corresponding page?

In my current project, I have developed a component that is utilized in an online science lab setting. To ensure continuity for researchers who navigate away from the page and return later, I have integrated the use of localStorage. The goal is to preserv ...

Obtain a Compilation of Video Sources in an HTML5 Format

Hey there, I am using an HTML5 video. This is just an example <video width="320" id="video" height="240" controls> <source src="video.mp4" type="video/mp4"> <source src="video1.mp4" type="video/mp4"> <source src="movie.ogg" typ ...

Is it possible for the req.url path in expressjs to represent a different URL?

Recently, I discovered some suspicious requests being sent to my node-express server. In response, I created a middleware to record the request URLs. After logging these requests, I noticed that most of them started with '/', but there were also ...

Tips for effectively crafting a component capable of managing both a value and an observable for that specific value

I'm actually curious about two things. When is it appropriate to pass an observable of an object into a component versus resolving it with the | async method? If I want to create a versatile reusable component that can handle both scenarios - accept ...