The Spring controller receives only the initial index of the stringified array from Ajax

Below is the complete JS code snippet:

function getPoolsData(){
$.getJSON('../json/data.json', function(data) {

var date_from = new Date();
console.log(date_from);
var pools_hashrates = [{"date_from" : date_from}];

data.pools.forEach(function(pool){

var api_url = pool.api;
var poolName = pool.name;

if(pool.type == "forknote"){

    $.getJSON(api_url + 'stats', function(data) {

            var poolHashrate = data.pool.hashrate;

            pools_hashrates.push({"poolName" : poolName, "hashrate" : poolHashrate});

            console.log("Pool name: " + poolName + " Pool hashrate: " + parseInt(poolHashrate));
    });
}
else{
    $.getJSON(api_url + 'pool/stats', function(data) {

            var poolHashrate = data.pool_statistics.hashRate;

            console.log("Pool name: " + poolName + " Pool hashrate: " + parseInt(poolHashrate));

            pools_hashrates.push({"poolName" : poolName, "hashrate" : poolHashrate});

    });
}

});

console.log(pools_hashrates);

$.ajax({
  type: "POST",
  contentType : 'application/json; charset=utf-8',
  dataType : 'json',
  url: "/save",
  data: JSON.stringify(pools_hashrates),
  success :function(result) {
      console.log("Success!");
 }
});

});
}

Here's how the controller method looks like:

@RequestMapping("/save")
public @ResponseBody String getPoolsData(@RequestBody String string){

    System.out.println("Triggered: " + string);
    return "Success mvc";
}

And this is the output from the controller:

Triggered: [{"date_from":"2018-04-13T11:05:00.652Z"}]

The issue at hand is that only the first index of the array is being sent to the controller, even though the array contains around 20 items. The entire array is displayed when console.log(pools_hashrates) is called. The script is triggered by a button.

Answer №1

When making Ajax calls, it's important to note that they are asynchronous. This means that all 3 calls will be fired off simultaneously and the call to getPoolsData will not wait for the get request to finish. To ensure that Ajax calls are executed asynchronously, you can set them up like this:

$.ajaxSetup({
    async: false
});

Keep in mind that setting all Ajax calls to be synchronous might not be the best approach. It would be more efficient to rewrite your calls as follows:

$.ajax({
    url: "...",
    type: "GET",
    data: ...,
    async: false
});

This way, only specific calls will be made asynchronously. Another option is to use setInterval to monitor jQuery.active and initiate a new Ajax call once it reaches zero:

var myTimer = setInterval((function(){ 
    if (jQuery.active == 0){
        $.ajax({
            type: "POST",
            contentType : 'application/json; charset=utf-8',
            dataType : 'json',
            url: "/save",
            data: JSON.stringify(pools_hashrates),
            success :function(result) {
                console.log("Success!");
            }
        });
        clearInterval(myTimer);
    }
}, 1000)); // Check every second if there are active Ajax calls

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

Using the ng-repeat directive in an angular-nvd3 tooltip

Looking to dynamically repeat values in the tooltip content of an nvd3 graph? Not sure how to achieve this using ng-repeat with JSON data? Seeking guidance on alternative methods? I can help! $scope.options = { chart: { type: ...

leveraging embedded jetty for developing a web-based interface

As a newcomer to web development and using embedded Jetty, I have created the source code below in Eclipse IDE. I need to programmatically start the Jetty server and cannot use the command line to do so. The web interface must be lightweight due to the li ...

What is the best way to instruct Vite to exclude specific files within a directory from the build process?

After initializing a fresh Vue application with the command npm create vue, I implemented a functionality where the app fetches a configuration at runtime and extracts a component name from it. These dynamic components reside in a directory called "pluggab ...

adding the authentication token to the Dropzone configuration for headers

I am tasked with including the header access token. $scope.dropzoneConfig = { 'options': { // passed into the Dropzone constructor 'url': 'SOME API URL' + $scope.SOME_ID }, 'eventHandlers': { ...

Unleashing the power of JSON decoding: Enforcing the transformation into

I have a Go struct where I need to unmarshal JSON data, everything works correctly except for the Values map which is of type map[string]string. type Data struct { Id int `json:"id"` Values map[string]string `json:"value ...

Having Trouble with Sending Emails Using Google Scripts - Javascript POST Request Issue

I have been working on setting up a basic form on my website where users can input their name, email, and a short message. This information is then sent to Google Apps Script which forwards the message to me via email. Unfortunately, I keep encountering an ...

Android: Dynamically Populate ListView with JSON Data based on selection from 2 Spinners

Before taking any action, please refrain from closing or marking this question as a duplicate. The scenario presented here is unique and distinct from others previously discussed. I have thoroughly reviewed all relevant information for almost three weeks b ...

"Discover the steps to efficiently utilize the lookup feature with array objects in MongoDB

I am a beginner with MongoDB and I am trying to create a schema for my collection as shown below please note that all ObjectId values are placeholders and not real stockIn documents { serial:"stk0001", date:'2021-06-11', productInTra ...

Ways to extract only numbers from a string

I have encountered a frustrating issue in VueJS: I am receiving an object with the following structure: { "description": "this is our List.\n Our Service includes:\n-1 something\n-2 something else\n and another thing\n"}` My dile ...

Using Vue/Nuxt.js to compute the cumulative sum of hierarchically structured JSON data

When using Nuxt async data, I am retrieving a JSON object that includes a nested array in the following structure: "topic_list": { "topics": [ { "id": 9148, "title": "A", "views": 12 }, { "id": 3228, ...

Angular allows for a maximum time span of 60 days between two date inputs

I am looking to implement a validation in JavaScript or TypeScript for Angular where the start date cannot be more than 60 days after the end date is entered. The requirement is to enforce a "maximum range of 60 days" between the two input dates (dateFro ...

Is there a more streamlined method to use a "Walk" JSON response to automatically fill form fields?

Is there a more elegant and efficient way to achieve this task using jQuery instead of PHP and foreach? I want to walk through the var/val pairs of a JSON response and populate form fields with the same id's as the field names in the JSON. Here is th ...

Is there a way to determine the items that will be displayed on this page by clicking a link from a different page?

First Page: Whenever a link is clicked, it will redirect to the second page where only the relevant item will be displayed <ul class="portfolio-filters list-inline"> <li ><a href="page2.html/#webdesign-filter">Web ...

Quiz results are incorrect

I've been working on creating a quiz application using JavaScript only, but I'm encountering an issue with the scoring. Initially, I set the correct variable to 0 and intended to increment it by 1 each time a correct answer is selected. However, ...

A Vue button that toggles between three states depending on the value in an array

In my Vue project, I am working on loading an array when the page loads. I need to check the status of each line item in the array and display a specific button for each status using a 3-way toggle. Although I believe I understand the main concept, I am s ...

How to implement a feature for uploading multiple files through a single form with unique input fields in a web

After searching on Stack Overflow, I couldn't find a suitable solution for my problem. I need help with my code that fetches data and sends it to a PHP file to upload files to specific folders and store their links in a database. However, I am encount ...

Utilizing React with Material UI, implement a Select component while disabling the scroll lock and ensuring the menu is positioned relative to

import React from "react"; import "./styles.css"; import Input from "@material-ui/core/Input"; import MenuItem from "@material-ui/core/MenuItem"; import FormControl from "@material-ui/core/FormControl"; import Select from "@material-ui/core/Select"; cons ...

Sending a `refresh` to a Context

I'm struggling to pass a refetch function from a useQuery() hook into a context in order to call it within the context. I've been facing issues with type mismatches, and sometimes the app crashes with an error saying that refetch() is not a funct ...

What is the best way to include the parameter set in the interceptor when making a post request?

-> Initially, I attempt to handle this scenario in the axios request interceptor; if the parameter is uber, then utilize a token. If the parameter is not uber, then do not use a token. -> Afterward, how can I specify uber as a parameter in the custo ...

It appears that the .fadeOut() function is not working properly when applied to an image

I want my input text box to automatically submit the form and display a checkmark image after the user has been idle from typing. I tried implementing a fadeout function for the image but it doesn't seem to be working. var timer = null; $('.form ...