Calculate and retrieve the result from the event handling function

I need to capture a returned value and store it in a variable within an event handler function.

Below is a sample code snippet demonstrating this:

var xhr = new XMLHttpRequest();
    
function getData(e) {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            e = JSON.parse(xhr.response);
            return e;   
        } else {
            return alert("Error!!");
        }
    }
}

var data;
xhr.addEventListener("load", function () {getData(data);}, true); // store the result in the 'data' variable
console.log(data);

Answer №1

Give this a shot:

xhr.onload = function(){
if(xhr.readyState == 4 && xhr.status == 200){
    //call a custom function to process the response data function(xhr.responseText)
}
};

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 integration of OCS in a SharePoint web part using AJAX technology

Currently, I am working on a web part that utilizes AJAX to display search results. The results include usernames with OCS presence indicators displayed opposite each name. While the indicator works fine in IE6, unfortunately, it does not function properly ...

Extending a Typescript class from another file

I have a total of three classes spread across three separate .ts files - ClassA, ClassB, and ClassC. Firstly, in the initial file (file a.ts), I have: //file a.ts class ClassA { } The second file contains: //file b.ts export class ClassB extends Class ...

Filtering an Array of Objects on the Fly in Vue.js

I'm currently working on a Vue.js app where I need to dynamically apply filter values to an Array of objects based on their field values. Each object in the Array has various fields that I want to filter by. The challenge is that each field can have m ...

Using Vue components in NativeScript-Vue popups: A comprehensive guide

To initiate the popup, I include the following code in a root component: import parentt from "./parentt.vue"; . . . this.$showModal(parentt, { fullscreen: true, }); The contents of parentt.vue are as follows: <template> <StackLayout> ...

Ajax: everyone utilizing a rapid application development (RAD) tool

Looking for recommendations on a RAD tool for AJAX interface programming. Has Grails been effective for this task? ...

Tips for utilizing a unique JavaScript function with Mongoose's findByIdAndUpdate by incorporating $set:

Is it possible to update a database document using a custom JavaScript function? I am aware of the traditional method where you find -> update the document with JavaScript -> save, but this can lead to issues with concurrent data updates. Below is an examp ...

Azure-Graph is reporting an error: 'Invalid or missing Access Token.'

In my Node.js project, I effortlessly integrate azure APIs. Logging in: const MsRest = require('ms-rest-azure'); MsRest.loginWithServicePrincipalSecret(keys.appId, keys.pass, keys.tenantId); Creating a resource group: const { ResourceManageme ...

Securing the connection between clients and servers through encryption

For my mobile client, I am using Xamarin, with node.js as my backend and MongoDB as the database. The main issue I am facing is how to securely store user data in the database. If I only do server-side encryption, there is a risk of hackers intercepting th ...

A compilation of approved classes for the quill toolbar

The instructions provided in the documentation for the quill module indicate that you can manually create a toolbar using HTML, and then pass the corresponding DOM element or selector to Quill. This will result in the ql-toolbar class being added to the to ...

Issue with reactivity not functioning as expected within VueJS loop without clear explanation

Struggling with implementing reactivity in vue.js within a loop? The loop renders fine, but firing an event updates the content without visibly rendering the data on the page. The latest version of vue.js is being used with bootstrap and jquery. Despite a ...

When working with Firebase, I am required to extract data from two different tables simultaneously

When working with Firebase, I have the need to extract data from tables/nodes. Specifically, I am dealing with two tables - one called jobs and the other called organisations. The outcome I am looking for: I want to retrieve all companies that do not hav ...

How can you decode JSON using JavaScript?

Need help with parsing a JSON string using JavaScript. The response looks like this: var data = '{"success":true,"number":2}'; Is there a way to extract the values success and number from this? ...

Controlling the Quantity of Selected Checkboxes with JavaScript

I am facing an issue with implementing multiple checkboxes with limits in JavaScript, as shown below. $(".checkbox-limit").on('change', function(evt) { var limit = parseInt($(this).parent().data("limit")); if($(this).siblings(':checked&ap ...

Issue found: React-Redux action is not being dispatched

I'm currently working on setting up Google authentication in my React Next.js application. The process involves sending the access token to my backend, where it is validated before a new token is returned in the header for accessing protected resource ...

Where should uploaded files be stored using ng-flow?

Initially, I am utilizing the ng-flow, which is an html5 file upload extension built on the angular.js framework. After uploading my files and logging the event in the console, I'm uncertain about where and how to store them. Below is my HTML code w ...

Steps for creating a resizable and automatically hiding side menu

I am working on a side menu that can be resized, and I want it to collapse (set to zero width) when it is empty. I have considered implementing one of these features individually, but I'm not sure how to make both work together. Is there a way to ad ...

Using Flask to pass variable data from one route to another in Python using the `url

I am facing an issue with sending a variable value to Python from Flask HTML/JS via url_for(). Here's my Python code: @app.route('/video_feed/<device>') def video_feed(device): # return the response generated along with the speci ...

Incorporating the power of ES6 into a pre-existing website using React

I currently have an established website with a page accessible through the URL www.example.com/apps/myApp. The myApp functionality is embedded within an existing HTML page and serves as a utility app. I am interested in learning React, so I see this as a g ...

What is the equivalent of jQuery's blur event in AngularJS?

I need to implement a functionality in AngularJS where any opened component is closed when clicking outside of it. Is there an existing Angular directive for handling blur events, or do I need to come up with a custom solution? ...

Utilize HTML5 to enable fullscreen functionality for embedded SWF files

I have implemented a function that handles the click event of a button to toggle a DOM element into fullscreen mode. The function works well, but I am facing an issue when there is another div containing a swf inside the main div. var elem = document.getE ...