Is it possible to retrieve a value from an xhttp request?

I am currently working on an xhttp function that interacts with my database and returns an array. The content of the array varies based on the parameter provided in the xhttp function during its execution. Below is the code snippet for the xhttp function:

fetchGroupInfo: function (groupNum) {
                var global = this;

                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {                                                       
                    if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status == 200) {
                        console.log(this.responseText);
                        var rawdata = this.responseText;
                        var json = JSON.parse(rawdata); 
                        return json;
                    }
                };

                xhttp.open("GET", "http://178.62.***.***:1020/groupInfo/"+groupNum, true);
                xhttp.send();
            },

In order to avoid repeating this function multiple times to fetch different arrays, I aim to streamline it for cleaner code in future instances. Here's a sample of what I envision doing:

this.group1Info = this.fetchGroupInfo(1);
this.group2Info = this.fetchGroupInfo(2);
this.group3Info = this.fetchGroupInfo(3);
this.group4Info = this.fetchGroupInfo(4);
.....

Currently, the function returns an undefined value. What would be the correct approach to make this work effectively?

Answer №1

To ensure proper handling of your asynchronous code, you need to include a callback function and assign your variables within the callback:

retrieveGroupData: function (groupNumber, callback) {
            var instance = this;
            
            var httpRequest = new XMLHttpRequest();
            httpRequest.onreadystatechange = function() {                                                       
                if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status == 200) {
                    console.log(this.responseText);
                    
                    var rawData = this.responseText;
                    var jsonData = JSON.parse(rawData); 
                    return callback(jsonData);
                }
            };

            httpRequest.open("GET", "http://178.62.***.***:1020/groupInfo/"+groupNumber, true);
            httpRequest.send();
        }

To set the variables after calling retrieveGroupData, make sure to pass a callback function each time:

this.retrieveGroupData(1, function(result) {
  this.groupOneInfo = result;
});

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

Leveraging jQuery Ajax and MySQL to generate dynamic HTML content

I'm in the process of creating a unique photo gallery that utilizes dynamic features. Instead of relying on constant HTML/PHP refreshing for updates, I am incorporating jQuery to handle dynamic MYSQL queries. As a beginner, I've managed to creat ...

Maintain only specific elements in jQuery by filtering out the rest

Here is a scenario with a page layout to consider: <div id="page-container" class=""> <div id="scroller"> <!-- This page should be removed --> <div id="page_1" class="pagina"></div> <!-- These pages should be kept --&g ...

Excruciatingly tardy performance from Node, Apollo, and Sequelize (over 7 seconds)

Although I'm more comfortable with Laravel, I am experiencing a delay of approximately 7.2 seconds when running a single query in Apollo Server for around 300 items. The resolver code provided below seems to be fairly straightforward and only involves ...

Generating dynamic div elements using jQuery

I am currently working on developing a button that will automatically generate pre-formatted divs each time it is clicked. The divs consist of forms with fields that should already be populated with data stored in JavaScript variables. Example: <d ...

Steps for recreating a Jquery Mobile form element with the same name after destroying it

As I delve into Jquery Mobile, I encounter a scenario where I must dynamically generate form fields (select, input, etc) using the following approach: $fieldInput = $('<input type="text" name="' + fieldName + '" />'); Initially, ...

Unable to interact with anchor link

Currently, I am in the process of developing a new website that features a masonry/Pinterest style effect blog board. One issue I have encountered is that when hovering over a post, a button should appear to link through to the corresponding blog/single pa ...

Is it possible to dynamically add the URL to an iframe based on a condition being true, and then iterate through a list of URLs before

I'm trying to figure out how to change the URL in an iframe based on the presence of a class="show". The first time the element has the class "show," it should load about.html. The second time the same element has the class "show," it should open wor ...

The height of my row decreases when I implement the z-index for a hover effect

Hey there! I'm currently working on creating a hover effect for my cards using Bootstrap and z-index. However, I've run into an issue where the z-index works fine when I hover over the cards, but the row loses its height. I tried adding a height ...

Using jQuery to retrieve the nth child from a table after dynamically creating it with AJAX

When using AJAX in the code below, I fill and create simple data after retrieving it. $.ajax({ method: 'GET', url: '/analyzePage/searchTag/' + tagName, contentType: false, processData: false, success: function (data ...

issue encountered during the conversion from kml to geojson format

I've been working on converting a KML file to geojson for D3, but I ran into an issue: getElementsByTagName() is not a function when running the following script in my browser: <script> $.ajax('data/District.kml' ...

Tips for transferring JavaScript data to an ASP.NET MVC controller

This is my controller: public ActionResult GetFilterUsers(int pageNumber) { //...... } This is my js code: $('#users-data-table').DataTable({ serverSide: true, ajax: { url: "@(Url.Action("GetFilter ...

Guide for accessing Javascript documentation via console?

There are many times when I am coding in Python, that I find myself wanting to quickly access the documentation for a function. In the iPython console, I can easily do this by entering dir?? which retrieves the documentation for the dir function. Is ther ...

The loading time for the NextJS production build is unacceptably sluggish

Recently, I started working with NextJS and deployed my project on Netlify as a production build. However, I've noticed that there is a significant delay of around 3-4 seconds when navigating to a specific page using the next router. Surprisingly, thi ...

Overflow of text arranged horizontally within a span element situated inside a div container

I am currently working on developing a ticketing system that involves using nested div elements to organize content. Each ticket is represented by a main div containing various other nested divs and media such as images. While the functionality of the sys ...

Leveraging xgettext for extracting translatable content from VueJS files

Attempting to utilize xgettext for extracting translatable strings from a VueJS file has presented some challenges. Specifically, xgettext does not seem to recognize JavaScript code within a computed property in VueJS. For instance, consider the following ...

finding the ID of the element that triggered a jQuery dialog

I'm utilizing jQuery dialog to trigger popup windows when buttons are clicked. <script> $(document).ready(function(){ $("#dialog-form").dialog({ autoOpen : false, height : 300, ...

Obtain the title of the text generated by clicking the button using a script function

I am working on a piece of code that generates a text box within a button's onclick function. My goal is to retrieve the name value of each text box using PHP. <script language="javascript"> var i = 1; function changeIt() ...

Guide on setting up background sound notifications with firebase-messaging-sw.js

const audio = new Audio(" "); Whenever I include this code in my firebase-messaging-sw.js file for the service worker, I keep encountering a reference error. Even though notifications come through when the browser is in the background, an Audio is not de ...

Enhancing Function Calls for Better Performance in V8

Is V8 capable of optimizing repeated function calls with identical arguments? For instance, in the code snippet below, Variance is invoked twice with the same arguments. var Variance = require('variance'); function summary(items) { ...

Looking to execute a PHP file from HTML/JavaScript?

Greetings! I have a unique jQuery/javascript plugin that functions as a vertical ticker for news updates directly on my HTML website. Here is the code snippet: <script src="jquery.vticker-min.js"></script> <script type="text/ja ...