Utilize a function to save the data retrieved from each AJAX request

I am struggling to store accumulated data between ajax calls in an object. Even though I can retrieve the data from each call, I cannot seem to merge it into a single array.

To address this issue, I have devised the dataAccumulator() function. The intention is that by invoking accumData.append, the data from a solitary call will be added to the holding array.

Despite my efforts, I continuously encounter errors such as

Cannot read property 'append' of undefined
or
Uncaught TypeError: dataAccumulator is not a function
, regardless of where and how I define or employ the function...

Consider the following code snippet:

var inter;
var dataAccumulator = dataAccumulator(); //object of interest

function startTempMonit()
{
    $(document).ready(function()
    {
        time= 0;
        inter = setInterval(function()
        {
            $.ajax // ajax call starts
            ({ 
                //not relevant for the question. arguments removed...
            })
            .done(function(data) {
                //problem here. data is foreach call.
                //I would like to accumulate each of the data to handle the whole here.
                dataAccumulator.append(data);  
            });
            time= time + 0.5;
        }, 500)
    });
};

function dataAccumulator () {
    let accumData = [];
    console.log("accumData function created")

    function append(data) {
        accumData.push(data);
    
        console.log(accumData); //log the accumulated data each time
    }

    this.append = append;
};

It appears that my predicament revolves around JavaScript scopes. My objective is to maintain the accumData array accessible within the ajax call's .done function. This encapsulates the crux of my dilemma.

Answer №1

To start off, it's crucial to eliminate the use of global variables in your code. Following that, opt for utilizing events over maintaining a global state.

Set up a callback function that gets triggered each time new data is received. Proceed to process and handle the incoming data within this callback function.

function initiateTemperatureMonitoring(callback) {
    var time = 0;
    return setInterval(function () {
        $.ajax({ 
            url: '....',
            data: '.....' + time,
            dataType: '.....',
        })
        .done(function (data) {
            console.log("received", data);
            callback(data);
        });
        time += 0.5;
    }, 500);
}

$(function () {
    var inter, accumulatedData = [];
    
    $("#buttonStart").click(function () {
        inter = initiateTemperatureMonitoring(function (data) {
            accumulatedData.push(data);
            // Perform additional actions such as updating a table or chart
        });
    });
    $("#buttonStop").click(function () {
        clearInterval(inter);
    });
});

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

Issue with displaying the Bootstrap-select DropDownList

Within my web application, I have a bootstrap-select combobox that I populate with data using an ajax call. Html: <div class="row"> <select id="selectGemeente1" class="selectpicker" data-live-search="true"></select> </div> Ajax ca ...

What are the steps to create a responsive Coin Slider?

Once the slider is generated, it appears that there is no built-in method to resize it, causing issues with responsive design. Is there a way to adjust the size of the Coin Slider plugin based on the media queries in Twitter Bootstrap 3? Take a look at C ...

Is it feasible to send an AJAX POST request to a server with a distinct domain while utilizing basic authentication?

I have encountered an issue while attempting to send a POST request to a server with a different domain that necessitates basic authentication. Despite my best efforts in experimenting with beforeSend and withCredentials, the basic auth headers do not get ...

Unexpected loading glitches occurring in vue-material components

I recently delved into the world of Vue.js and VueMaterial, which has been a refreshing and new experience for me since I've mostly focused on Native Android development in the past. Currently, I'm facing an unusual issue that seems to stem from ...

Having trouble removing just one element from an array in Redux. Any suggestions on how to make it work properly?

I'm currently working on creating a dynamic algorithm for removing an item from an array. Reducer: import { LOAD_PAGES, REMOVE_PAGE } from "./dynamicMenuActions"; export const initialState = { pages: [] }; export const dynamicMenuReducer = (state ...

I keep fetching data from the server using my vue.js code

Vue.js is new to me and I'm still trying to grasp its concepts (please ignore the indentation in the code) methods:{ getdata() { if (this.myPage.month === 5) { axios.get("http://www.amock.io/api/maymock").then(response => { this.Month ...

Exploring through a table using JavaScript

I am struggling to search a table within my HTML for a specific term. The code I have works to an extent, but it does not account for alternatives such as searching for "what is that" when I type in "What is that". Additionally, I need the script to ignor ...

PHP Error: AJAX request for URL failed due to incorrect address

While migrating my application to a new server, I have encountered some issues. The PHP version is 5.5.34 and the Mac OSX Apache version is 2.4. The Laravel version being used is 4.2. Although I am able to get a grid, my browser is generating URL-related ...

Is it possible to eliminate the default placeholder text from Safari browser?

My goal is to design a form that includes date and time input fields. The placeholder text should move up by X pixels when the user clicks on the field. While the form appears fine in Chrome, there seems to be an issue with overlapping form fields in Safa ...

Determining the type of <this> in an Object extension method using TypeScript

I am attempting to incorporate a functionality similar to the let scope function found in Kotlin into TypeScript. My current strategy involves using declaration merging with the Object interface. While this approach generally works, I find myself missing ...

What is preventing the text of the elements from being updated?

My attempt to use JavaScript to change the text of this element has not been successful. The header I am trying to modify is enter image description here var elem = document.getElementsByClassName("headertext"); elem.innerHTML = "hello world"; <ul cl ...

Asynchronously retrieving data in .NET using Angular

Initially, I am attempting to retrieve all projects from the database based on the provided userId from the URL. This operation is performed in the ngOnInit() lifecycle hook. Each project contains a field named Languages, which represents a list of objec ...

Tips for positioning a React component above another component

I am currently facing a challenge while working on a table with an expand more option to display additional details for each specific row. I have implemented a slider to facilitate the expansion of the table. Presently, my ExpandToggle component is embedde ...

When utilizing the tab key on Chrome, the iFrame fails to scroll

We are currently facing an issue with our web application that is embedded inside an iFrame. On one of our HTML pages, there are numerous textboxes with a large amount of content, requiring users to scroll down to navigate through it all. When using the ...

Ways to troubleshoot setTimeout functioning during HTTP requests?

Utilizing Socket IO in my client app, I have implemented a feature to check for unread events. The process involves making a request to the backend, which then sets a 5-second timeout before checking for any new events and sending them back. // client soc ...

Is there a way in PHP to automatically refresh a webpage at a specific time interval?

<?php $page = $_SERVER['PHP_SELF']; $sec = "10"; date("Y-m-d"); date_default_timezone_set('Asia/Kolkata'); $time= date('H:i'); if($time == '11:51') { echo mt_rand(0,9); echo '<br>'; } ? ...

Generate an array of checked inputs to be used when posting to a REST API

I have been using .push() to create a checked array of "List" inputs for posting to a REST API. However, it doesn't seem to be working correctly. When unchecking an item, it is not automatically removed from the array. Does anyone have a better solut ...

`The resurgence of CERT_FindUserCertByUsage function in JavaScript`

I am currently grappling with unraveling the connection between C++ dlls and JavaScript. There is a snippet of js code that reads: cert = CERT_FindUserCertByUsage(certDB, certName.nickname,certUsageEmailSigner, true, null); where the variable cert is ini ...

Breaking Down the Process of Exporting a Next.js Static Website into Manageable Parts

I am facing memory issues while building my website using Next.js's Static HTML Export. The site has a large number of static pages, approximately 10 million. Is it feasible to export these pages in batches, like exporting 100k pages in each build ite ...

Storing the background color in a JavaScript variable

I've been experimenting with creating a fade in and out effect for a background image on a website. I've also been attempting to capture the background color of a div and store it in a variable. Here's what I have tried: elem = document.ge ...