Sending a JSON array from an Ajax request to a Spring controller: A step-by-step guide

My HTML table data is converted to JSON format and sent via AJAX to a Spring controller. In the controller, I used

@RequestParam Map<String, String>
to retrieve the values, but the entire JSON string was received as the only key. I cannot use a model class due to different scenarios, so I need the column headers along with their values.

<table>
<thead>
<tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
    <td>A1</td>
    <td>A2</td>
    <td></td>
</tr>
<tr>
    <td>B1</td>
    <td>B2</td>
    <td>B3</td>
</tr>
<tr>
    <td>C1</td>
    <td></td>
    <td>C3</td>
</tr>
</tbody>

The HTML table data is transposed into JSON format and transmitted through AJAX.

  [
    {
    "Column 1": "A1",
    "Column 2": "A2",
    "Column 3": ""
    },
   {
    "Column 1": "B1",
    "Column 2": "B2",
    "Column 3": "B3"
   },
   {
    "Column 1": "C1",
    "Column 2": "",
    "Column 3": "C3"
   }
  ]

AJAX snippet -

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

Spring controller logic -

  @RequestMapping(value = "/gDirecotry/{id}", method = RequestMethod.POST)
  public @ResponseBody ModelAndView 
      getSearchUserProfiles(@PathVariable("id") String id,
                                 @RequestParam Map<String, String> 
   attributeMap) throws IOException {

return new ModelAndView("redirect:/home");
  }

I aim to map the JSON data to map<string,string>, how can this be achieved?

OUTPUT : I received the whole string as a single key without any associated value.

[{"Column 1":"A1","Column 2":"A2","Column 3":""},{"Column 1":"B1","Column 
2":"B2","Column 3":"B3"},{"Column 1":"C1","Column 2":"","Column 3":"C3"}]

Answer №1

Modify:

@RequestParam Map<String, String> attributeMap

Into

@RequestBody List<Map<String, String>> attributeMap

The data you are sending in the form of JSON is an array containing objects.

Answer №2

Here is an example for an array of objects.

Controller:

@RequestMapping(value = "updateProfileRequests.do", method = RequestMethod.POST)
@ResponseBody
public Boolean updateRequests(@RequestBody ProfileAccessRequestResponseVO[] requests) throws Exception  {
    List<ProfileAccessRequestResponseVO> requestList = Arrays.asList(requests);
    controllerService.updateProfileAccessRequests(requestList);
    return true;
}

Ajax:

updateRequests = function (){
var dataArray = new Array();
    
for(var i = 0; i < 10; i++){
 var data = {};
 data.id = i
 data.desc = "test" 
 dataArray.push(data)
}

    $.ajax({
            type: "POST",
            dataType: 'json',
            contentType: 'application/json', 
            data: JSON.stringify(dataArray),
            url: "./updateProfileRequests.do",
            success: function (dataR) {
               return dataR
            },
            error: function(errorMessage) {}
          });
};

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

"Ways to retrieve an array of dates within a specified range of date and time

I am working with date fields in my project { tripScheduleStartDate: '2018-12-05T18:30:00.000Z', tripScheduleEndDate: '2018-12-07T18:30:00.000Z', } Is there a way to generate a datetime array from the start date to the end date, lik ...

Difficulty arises when collapsed text in Bootstrap clashes with the footer design

Hey there! I'm working on this website using Bootstrap, and I've encountered a problem. When you click the "See Wikipedia" button, the content expands and overlaps the footer in a strange way without changing the page height. I've tried adju ...

Passing PHP data to a JavaScript file using JSON格式

I have a query regarding how to pass php variables and send their values to a js file using json. Here is what I currently have: <?php $data = array('artist' => $artistname, 'title' => $songname); echo json_encode($data); // ...

Tiny adjustment to jQuery Collapsible Panel

I have successfully implemented a jQuery Accordion in my demo. When I click on 'About Us', it reveals the 'Team' link below. Exciting! Now, I am wondering if it is possible for this Accordion to function without needing the 'item& ...

Notifying the view with a SignalR message from the controller upon event trigger

Just starting out with SignalR and attempting to set up a notification for a specific event triggered by an API. What I've attempted: Hub: public class NotificationHub : Hub { private static IHubContext hubContext = GlobalHost.Connectio ...

Unable to display SVG icon in Highcharts rendering

Is there a way to add a specific symbol in SVG format to a graph using Highcharts? Highcharts.SVGRenderer.prototype.symbols.download = function (x, y, w, h) { var path = [ "M19 5v14H5V5h14m1.1-2H3.9c-.5 0-.9.4-.9.9v16.2c0 .4.4.9.9.9h16.2c.4 0 ...

Load link dynamically using the rel attribute

I am trying to implement dynamic content loading using jQuery's .load() function. The links are stored in the .rel attribute of the anchor tags. My setup looks like this: <script> $(document).ready(function(){ $('.sidebar_link').clic ...

Encountering difficulty accessing the object from the props within the created method

After retrieving an object from an API resource and storing it in a property, I encountered an issue where the children components were unable to access the object inside the created method. This prevented me from assigning the values of the object to my d ...

Using the innerHTML property to place an Img tag within a div element

I'm facing an issue with including multiple tags within a div using innerHTML. To better illustrate my problem, here's an example: var y = "jack.jpg"; var x = "Jack"; var f = "Hello world!"; document.getElementById("maindDiv").innerHTML += "< ...

Slideshow: I hope the Radio Button triggers the appearance of the next item in the rotation

I need to implement a carousel that displays the next item (Id="item2") when a specific radio button (Id="item1") is selected by default and another radio button (Id="item2") is pressed. Ideally, I would like to achieve this ...

Differences in file loading in Node.js: comparing the use of .load versus command-line

Currently, I am in the process of developing a basic server using vanilla JavaScript and Node.js. For this purpose, I have created a file named database.js, which includes abstractions for database interactions (specifically with redis). One of my objecti ...

Eliminate redundant tags using jQuery

I have a code snippet that I need help with. I want to check for duplicates and if found, display an alert stating that it already exists so users can't insert the same word/tag again. Can someone please assist me? <div id="tags"> <span>a ...

Exploring ways to retrieve a video thumbnail with VueJS3

I am currently working on a project to create a simple program that retrieves movies from my AWS-S3 bucket and transforms them into picture thumbnails. Below is the code I have written: <template> <img :src="imgURL" class="card- ...

Verify that all images have been loaded via AJAX before displaying them on the page

After thinking my project was complete, I encountered a problem when pushing the code live. While it worked perfectly on my local server, the images now take half a second to load properly causing a page thumbnail to pop up over a loading image. https://i ...

Echarts: Implementing a Custom Function Triggered by Title Click Event

I recently created a bar graph using Echart JS, but I'm struggling to customize the click event on the title bar. I attempted to use triggerEvent, but it only seems to work on statistics rather than the title itself. JSFiddle var myChart = echarts.i ...

execute a postback to refresh UpdatePanels

My webpage has a jQuery modal that pops up when a button is clicked. After performing some logic in the WebMethod called by this button, I need to refresh multiple update panels on the page to show the changes made. Although I am not very familiar with Up ...

Fetch the count of files in a directory using AJAX

I'm attempting to fetch the number of files in a folder and compare it with the maxfiles value. Within dropzone.js, there is a function that looks like this: Dropzone.prototype._updateMaxFilesReachedClass = function() { if ((this.options.maxF ...

Is it possible to set a different default page index other than 0 in a material table using reactjs?

I have noticed that the default page index in the material table is set to '0', but the API I am currently using begins with a page index of '1'. Is there a way to adjust the default page index of the table to match that of the API? ...

Upon the second access, unbind the Ajax Autocomplete and throw the jQuery Simplemodal

Currently, I am utilizing jQuery simplemodal to trigger a popup form that features AJAX autocomplete inputs. Upon the initial opening of the modal, these autocompletes function properly. However, after closing and reopening the modal, the autocomplete in ...

Disregard the sorting of rows in the MUI Datagrid

Any advice on excluding the "TOTAL" row from sorting in MUI library? onSortModelChange={(test, neww) => { neww.api.state.sorting.sortedRows = [14881337, 2, 3] neww.api.setState({...neww.api.state}) } } Review ...