Posting a string using AJAX to the Java backend through JavaScript

I'm currently working on a comment section for a Web Client.

There are two tables involved - one for the comments and another for the users. My goal is to send input data from HTML <input> tags to a Java Service where the data will be processed. However, I've encountered an HTTP-415 error and I'm stuck on how to resolve it.

The approach I am using involves AJAX in JavaScript to transmit the data.

HTML

ID: <input type="text" name="id" value="1" readonly/> <br/>
Author: <input type="text" name="author"/> <br/>
comment: <input type="text" name="comment"/> <br/>
<button id="submit" type="Button" >Submit</button>

Javascript

function addPost(givenID){
var $author = $("#author");
var $comment= $("#comment");
var $id = $("#id")

$("#submit").on("click", function(){

         var post = $author.val()+"*"+ $id.val()+"*"+ $comment.val();

    $.ajax({
        type: "POST",
        url: "api/kommentar",
        data: post,

        success: function(){
            console.log("SUCCESS");
        },
        error: function(){
           console.log("FAILURE");
        }
    });

});} 

Java

@Path("/kommentar")
public class KommentarService {

@EJB
private KommentarManagement postMgmt;

public KommentarService() { }

@POST  
@Consumes("text/plain")
public void addPostsAsJson(String income) {
    System.out.println(income);
 //CODE TO HANDLE...
}

Answer №1

When using jQuery's Ajax function, the default content type is 'application/x-www-form-urlencoded; charset=UTF-8'. However, if the service requires 'text/plain' as the content type, then it needs to be changed accordingly.

To specify a content type change, you can add the following line of code:

data: post,
contentType: 'text/plain',  //<--- insert
success: function(){

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

Implementing a transition effect to the drawimage function

I am currently working on implementing a transition effect for an image inside a canvas element. I have provided a snippet below to demonstrate my progress so far. Can anyone guide me on how to incorporate a transition animation for the image within the c ...

Steps for generating a time selection dropdown menu

My issue is with the functionality of my timepicker dropdown. Below is the code I am currently using: $(document).ready(function() { $('.timepicker-input').timepicker({ timeFormat: 'h:mm p', interval: 60, minTime: ' ...

Tips for transmitting HTML as a JSON object through the res.render function in expressjs

My issue involves a JavaScript function that returns an HTML element. I want to pass this element along for users to view as actual HTML, but it ends up appearing as a string with special characters like "<" and ">". For example, "<" appears as (& ...

Using Jest functions as object properties results in undefined behavior

I am faced with a challenge in my class where I need to mock an object along with its properties intercept(context: ExecutionContext) { const response = contect.switchToHttp().getResponse() // the chain that needs to be mocked if (response.headersSent ...

The synergy of Redux with scheduled tasks

In order to demonstrate the scenario, I have implemented a use-case using a </video> tag that triggers an action every ~250ms as the playhead moves. Despite not being well-versed in Flux/Redux, I am encountering some challenges: Is this method cons ...

What measures can I take to safeguard my ajax widget?

I am looking to develop a unique widget that will utilize an ajax API hosted on my server. This widget will be served by my server and placed on various 3rd party websites. It needs access to the hosting page's DOM to interact with form data, so it mu ...

Is there a way to use JavaScript to import several custom fonts at once?

Is there a way to import a long list of custom fonts as icons using Javascript? I have been obtaining the font list from an API, but importing them one by one with pure CSS using @font-face is time-consuming and difficult to maintain. @font-face { fon ...

uWebSockets supporting multiple concurrent user sessions

To keep things simple, let's assume that my server is running just one uWebSockets instance: struct UserData { uWS::WebSocket<true, uWS::SERVER> *ws; bool logged_in = false; ID user_id; }; uWS::SSLApp() .ws<UserData>( ...

Is it possible to implement pagination using 'useSWR' in combination with the contentful-client?

I am currently working on implementing pagination in a Next.js project using the useSWR hook. My approach seems to be functioning correctly, but I have a concern about caching due to the key parameter not being a unique string as recommended in the documen ...

What could be causing my default prop to not be transmitted to the child component in vuejs2?

Having trouble passing a default value to my Leaflet map child component before fetching the desired data from an API endpoint. I tried using country coordinates like latitude and longitude, but it's not working as expected. This is how I attempted t ...

Create individual account pages with specific URLs in Next.js

I'm currently working on developing a website that will feature individual user pages showcasing their posts and additional information. I'm facing some difficulty in figuring out how to generate new links to access these user accounts. For insta ...

What are the best techniques for iterating through this specific string format in a loop?

I received a response in the following format: [{"error":false,"getFriends":{"name":"iman2420","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e4c4a4c4e3e170d1f50170c">[email protected]</a>","is_online": ...

Discover the correct way to locate the "_id" field, not the "id" field, within an array when using Javascript and the MEAN stack

I am working on an Angular application that connects to MongoDB. I have a data array named books, which stores information retrieved from the database. The structure of each entry in the array is as follows: {_id: "5b768f4519d48c34e466411f", name: "test", ...

Enhancing a validation form with the 'onblur' event handler

Exploring the realm of JavaScript, I find myself intrigued by the concept of creating a validation form that activates upon clicking out of the input field. Implementing various techniques to integrate this feature into an existing form has been both chall ...

Incorporating CSS into React.js applications

I am currently working on a project using MERN.io. In my project, I am utilizing the React.js component Dropdown. However, the Dropdown component does not come with its own style and CSS, resulting in no styling at all. ... import Dropdown from 'rea ...

The second tab on Bootstrap5's tab content feature seems to generate an endless amount of white

I am working on a project where I need to display statistics for both the current month and year. To organize this data, I created a card with tabs for each - one tab for the month and another for the year. By default, the month tab is loaded first. Howev ...

monitoring the winstonjs logs and inserting additional parameters

Can an argument be injected into a log, like error, debug, or info, using the configuration of winston (createLogger)? I want to intercept the log and include an object in each log entry. ...

What is the best way to efficiently query a substantial dataset using Node.js in an asynchronous fashion?

I need to extract data from a mysql database by fetching 10 rows at a time until I reach 400k rows. To achieve this asynchronously, I am using recursion as shown in the code below: var migrate = function(offset, size) { Mysql.query(query, [offset, size] ...

Exploring an alternative perspective on successful login in angular.js

Today was the beginning of my project to convert a website to angular.js. The main page is served by index.html and includes ng-view for other views such as login and signup. Working closely with a backend developer, I have successfully integrated a rest c ...

What is the best way to incorporate setTimeout in a loop using Coffeescript?

window.onload = -> boxOrig1 = 10 boxOrig2 = 30 canvasW = 400 canvasH = 300 ctx = $("#canvas")[0].getContext('2d'); draw = (origin,dimension) -> ctx.clearRect(0, 0, canvasW, canvasH) ctx.fillStyle = 'rgb(200,0 ...