Send a personalized array from Javascript to a Spring Rest Service using Ajax

I am faced with the task of creating a POST request using AJAX in jQuery. This involves passing an array of objects, which I can achieve with the following code:

var actor = new Array();
for(var i = 1; i <= incr; i++) {
    actor.push({
        "name": document.getElementById("idAN"+i).value,
        "surname": document.getElementById("idAS"+i).value,
        "dateborn": document.getElementById("idAB"+i).value,
        "gender": document.getElementById("idAG"+i).value,
        "movie": datas
    });
    alert("actorX: " + actor[i-1].surname);
}
$.ajax({
    method: 'POST',
    dataType: 'json',
    data: { actors: actor },
    url: 'http://localhost:8080/movies/actors',
    success: function (rest) {
        alert("actor added");
    },
    error: function(rest){
        alert("actor not added");
    }
});

I have tried receiving the data with this Java method, but it doesn't seem to work. Can anyone provide assistance?

@RequestMapping(value = "movies/actors", method = RequestMethod.POST)
public ArrayList<Actor> addActors(@RequestBody Actor[] actors) {...}

After three days of struggling, I managed to resolve this issue with the help from the comments. The resulting Java method is as follows:

@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "movies/actors", method = RequestMethod.POST, headers="Accept=application/json")
public @ResponseBody ArrayList<Actor> add (@RequestBody Actor[] actors) {
    ArrayList<Actor> json = new ArrayList<Actor>();
    for(Actor A : actors) {
        System.out.println("Arrivo");
        serv.addActor(new Actor(A.getName(), A.getSurname(), A.getBorn(), A.getGender(), A.getMovie()));
        System.out.println("nomeAttore" + A.getName());
        json.add(A);
    }
    return json;
}

Furthermore, here is the updated post request:

$.ajax({
    method: 'POST',
    dataType: 'json',
    data: JSON.stringify(actor),
    contentType: "application/json; charset=utf-8",
    url: 'http://localhost:8080/movies/actors',
    success: function (rest) {
         alert("actor added");
    },
    error: function(rest){
        alert("actor not added");
    }
});

In particular, I made a change to a parameter value in the SQL query from databorn to born because the naming had to match the getBorn and setBorn methods. It was important for the object's parameter name in the JavaScript array (actor) to be consistent.

Answer №1

Are you encountering any error messages? The issue might be that you're omitting the step of serializing your data into JSON format. You could attempt the following:

data: { characters: JSON.stringify(character) }

Additionally, include:

contentType: "application/json; charset=utf-8",

This should resolve the problem.

UPDATE

Give this a try:

data: JSON.stringify(character),

Answer №2

Consider updating the following code snippet:

@RequestMapping(value = "movies/actors", method = RequestMethod.POST)

to:

@RequestMapping(value = "movies/actors", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)

To enable this change, you need to include the jackson dependency. If your project is using Maven, add the following dependencies:

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.6.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.6.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.6.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-hibernate4</artifactId>
      <version>2.6.1</version>
    </dependency>

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

Incorporating an external .htm file using javascript into a designated div element

I've been attempting to load an external .htm file into a div on my main page using the code below: <a href="#file.htm" onclick="$('#content').load('file.htm')">Link</a> While this works in Firefox, it doesn't se ...

Node.js UDP broadcast to subnet not working properly in Linux

Here is a simplified Node JavaScript code snippet for testing purposes. Click here to view the code on GitHub This code creates a socket for each interface address, calculates the subnet broadcast address, and then sends data every second for 4 seconds t ...

Trouble with Setting a Background Image in Ionic with Javascript and Angular

I'm having trouble getting my background image to display in this Ionic project using CSS. It works when I embed it directly into the HTML, but that's not an ideal solution. I vaguely recall something about using base64 for images, but I'm n ...

Inject Angular 2 component into designated space

I am working on a website that requires a settings dialog to be loaded in a designated area upon clicking a button. The settings dialog is a component that retrieves data from REST endpoints. I am hesitant to simply insert the component and hide it as I ...

Updating hidden days in FullCalendar using jQuery

When I am filtering my calendar by changing the start and end dates, event statuses, and other criteria, I use the following code: $("body").on("click", "#btnFilter", function() { startDate = $("#startDate").val(); endDate = $("#endDate").val(); ...

Encountering an ETIMEDOUT error while sending out large (10k) post requests with axios.all in a Node

I have implemented axios.all to make simultaneous post calls. Below is the code snippet: let postUrls = []; data.forEach(item => { const itemData = { stream: stream_name, key: item.serialNumber, addr ...

Different techniques for retrieving elements generated by ng-repeat from their containing parent

Let's keep it simple - imagine we have a directive called headSlides. This directive's template includes an image that is being repeated using ng-repeat: <img class="bg" ng-repeat="image in images" ng-src="{{image.src}}"> I need to access ...

Is it possible to transfer data from a JavaScript file to the Express server without relying on a form submission?

As a newcomer here, I apologize if I overlook any best practices. Currently, I am in the process of developing a sudoku game using express, JavaScript, HTML, and mongoDb. My current challenge involves setting up a statistics system. My goal is to send da ...

Is Click and Mousemove available for iPhones?

I am experiencing some difficulties with mouseover and click events. While they work fine on desktop and laptop web browsers, they do not seem to function on the Safari browser of an iPhone. Below is the code snippet causing the issue: <script type="te ...

Tips for creating a TypeScript function that only needs one property from an object

Looking to overcome the habit of using any in TypeScript, specifically when creating a function that adds or removes an item from an array. The key requirement is that the item must have an id property of type string. Here's how I currently have it im ...

Is this correct - a beginner querying with Java Spring using Autowired to connect to Hibernate and MySQL?

I am currently developing a small program that displays a numbered list of local train stops and prompts the user to input the number of the station they want to see the next arrival time for. However, I'm encountering an issue with the MySQL query n ...

Using Ajax BeginForm can result in the sending of multiple requests, even when only a single

Currently, I am developing a .NET ASP.MVC application and facing an issue in one of my views where I have implemented Ajax.BeginForm. In my _Layout.cshtml file, I have included two scripts in the following order: <script src="~/Scripts/jquery-3.1.1. ...

React Js month picker problem encountered

I am currently working on implementing a month picker using the library called react-month-picker The code is functioning correctly in React: https://codesandbox.io/s/react-month-picker-forked-84rqr However, when I tried to integrate the same code into a ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...

Executing a secondary API based on the data received from the initial API call

Currently, I am diving into the world of RxJS. In my project, I am dealing with 2 different APIs where I need to fetch data from the first API and then make a call to the second API based on that data. Originally, I implemented this logic using the subscri ...

What are the steps to execute algorithms in elki-tutorial-0.7.0.jar?

Executing elki's algorithm is as simple as this command: java -jar elki-bundle-0.7.1.jar Yet, how can different algorithms be run within elki-tutorial-0.7.0.jar? ...

Javascript clock problem, kick off on click

Currently working on a game and in need of a counter that starts when clicked and stops at 00 (From 1m to 00). It is currently starting onload and cycles back to start when it reaches 00. HTML: <body> <div> <div class="timer" >Battle t ...

Problem encountered when attempting to utilize the spread operator within .vue files in an Elixir Phoenix 1.3 application

I'm facing an issue while building Vue.js components that involve using the spread operator to map states from Vuex within my Phoenix 1.3 application. The JavaScript compile errors I encountered are causing some roadblocks: 26 | }, 27 | compu ...

"An ActionResult is received as null when the model is passed as an

Has anyone encountered a situation where the model is null when passed to the controller? I inserted an alert in the ajax call to verify the value and it seemed correct, but upon debugging on the first line of the controller's ActionResult, it shows a ...

Steps for applying numerous styles to the native element using Angular

Currently, I am attempting to implement multiple styles on the native element in Angular using the renderer2 API. I have a specific requirement where the styles need to change dynamically and there could be multiple styles involved. This is why I am avoid ...