The order of returned values may vary when sending a HashMap in an Ajax POST request

I am currently utilizing Spring as the backend for my application, along with Ajax to handle the fetching and posting of data. I have a situation where I am returning a HashMap from my controller and everything seems to be functioning correctly. However, upon receiving the data in my JavaScript file, the order of the data items is changing. What could be causing this issue?

For example, when I send

map.put("name","aaa");
map.put("name","bbb");
map.put("name","ccc");

In the JavaScript file, I observe a different order such as ccc, aaa, bbb. This changed order remains consistent and is not random.

Below are snippets of the code I am working with:

Controller

@RequestMapping(value = "/history", method = RequestMethod.GET)
public @ResponseBody Map<String, myModel> getHistory() {

    Map<String, ChatModel> userInfo = md.getUserInfo(userId);

    return userInfo;
}

Get method

$.ajax({
        contentType: "application/json;charset=utf-8",
        type : "GET",
        url : "../Spring4MVCHelloWord/history/",
        dataType : 'json',   
        success: function(data){

            displayHistory(data);
        },

         error: function(xhr, status, error) {
          console.log(xhr);
        }

    });

Answer №1

Consider implementing a LinkedHashMap for your solution. With a LinkedHashMap, you can maintain the order in which entries are added to the map. However, if performance is crucial and ordering is not necessary, then opt for a HashMap instead.

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 are the distinctions between performing React server-side rendering on a local machine versus on a live Node.js server like IBM Bluemix?

I successfully built a basic React app with server-side rendering using a workshop git as a foundation, along with some minor tweaks. Everything works smoothly when I run it locally with NODE_ENV=server node server.js. However, my attempts to deploy the ap ...

Issue: Unable to locate module 'js-yaml' while executing npm start command

Unable to locate module 'js-yaml' Require stack: D:\REACT NATIVE\portfolio\node_modules\cosmiconfig\dist\loaders.js D:\REACT NATIVE\portfolio\node_modules\cosmiconfig\dist\createExplore ...

What is the process for handling a List of WebElements with the "PageFactory.initElements(driver, this);" method?

I am curious about how PageFactory.initElements(driver, this) works to populate the searchSuggestions webElement. I have noticed that when I don't use thread.sleep(500), it throws a stale element reference exception, but with thread.sleep it works fin ...

Attempting to flip the flow of marquee loop in javascript

I am currently modifying this code to create a left-to-right marquee instead of the original right-to-left one. However, after successfully changing the direction, the text no longer loops as it did originally. I'm stuck and can't seem to figure ...

Tips for dynamically loading images as needed

I'm working on a simple image zoom jQuery feature using elevateZoom. You can see a Demo example here. The implementation involves the following code: <img id="zoom_05" src='small_image1.png' data-zoom-image="large_image1.jpg"/> <sc ...

Is it possible to retrieve local variable JSON arrays using ajax/getJson()?

When starting a project without a database or data source, I often create json arrays in a *.js file to populate screens until the data modeling or database creation is complete. I am trying to figure out how to write an ajax/getJson() function to access ...

Sending a object as an argument to a function

Could someone please help me understand the purpose of passing an object as a function parameter? I have been trying to learn Next.js and they frequently use this method in their code. If anyone could provide a brief explanation of why this is done, it wo ...

Nesting / Mulled / JS - Uploading Files - Form's end is unexpectedly reached

I have successfully implemented the upload file functionality in my Nest.js server application, but I am facing an issue when trying to use it with JavaScript/React. @Post('upload') @UseInterceptors(FileInterceptor('file')) upl ...

Convert the jade file to an HTML file while keeping the original file name

I'm currently attempting to configure Jade in a way that allows me to save my Jade files as HTML files while retaining the same file name. For example, I would like the file views/index.jade to be saved as dist/index.html This should apply to all ad ...

transmitting information via submission with the help of colorbox ajax

HTML <div class="cus_input"> <form id="category_form" method="GET" action="<?php echo base_url(); ?>welcome/find/" > <input type="text" id="category_input" name="q" placeholder=" Find Category"/> <a type="su ...

Callback function triggered upon the creation of a DOM node

I am in search of a way to have a specific callback function run each time a div that matches a particular selector is added to the DOM. I have explored the DOM events documentation and the event closest to what I need seems to be "load", however, it does ...

Tips for transferring data between pages in VUE js using paths

I currently have two pages - an add page and an edit page. I am looking to transfer data from the edit page to the add page. When the save button is clicked in the edit page, it should redirect the user back to the add page with a URL of /test/admin/testin ...

Guide to implementing 301 redirection from HTTP to HTTPS in Next.js

What is the process for implementing a 301 redirection from HTTP to HTTPS in Next.js? One example of this would be redirecting from "http://stackoverflow.com/" to "https://stackoverflow.com/". ...

What steps can I take to stop the browser from refreshing a POST route in Express?

Currently, I am using node along with stripe integration for managing payments. My application includes a /charge route that collects various parameters from the front end and generates a receipt. I am faced with a challenge on how to redirect from a POST ...

Checking conditions sequentially in Angular

I have a unique use case that requires me to verify certain conditions. If one condition fails, I should not proceed to the next one. Instead, based on the failed condition, I need to display a dialog with a title and description explaining what went wrong ...

Not sure how to configure the settings for Firebase Firestore within the admin.firestore module

When trying to set an option at admin.firestore, I couldn't find the set method. It should be done like this: const settings = {timestampsInSnapshots: true} admin.firestore.settings(settings) However, I encountered a TypeError: Firestore.settings is ...

Using VueJs to invoke a plugin from a .js file

I'm seeking a deeper understanding of working with vueJS. My current setup In my Login.vue component, there is a function logUser() from UserActions.js which in turn calls the postRequest() function from AxiosFacade.js Additionally, I use a plugin ...

modifying the source of an Ajax POST request

Is it possible to modify the referrer in an HTTP Ajax call using jQuery or JavaScript? I'm looking to send a request from my page but have the referrer appear as though it came from another page. Any insights would be appreciated. ...

Locate the unique identifier for the initial product with a special badge on an online retail platform through the use of Selenium

To complete the task of finding the top-selling women's socks on Amazon, I attempted to locate the item labeled as a "Best Seller" after searching for "Socks for women" on the website. However, I am struggling with the logic to identify and click on t ...

Error in Typescript: A computed property name must be one of the types 'string', 'number', 'symbol', or 'any'

Here is the current code I am working with: interface sizes { [key: string]: Partial<CSSStyleDeclaration>[]; } export const useStyleBlocks = ( resolution = 'large', blocks = [{}] ): Partial<CSSStyleDeclaration>[] => { cons ...