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

Tips for increasing the size of a textarea

I'm attempting to extend a textarea by adjusting the margin-top property, but it doesn't seem to be working as intended. Here is the code snippet in question: #sqlcontainerLoggedInPage2 { margin-top: 60px; } <div class="container-fluid" i ...

Is my $.getJson function triggering another action in my project involving adding items to the cart?

Here is my code in the view page: <form method="post"> <input id="Submit1" type="submit" value="Deleteallcarts" /> </form> <input type="submit" class="product_btn" value="Buy Now" /> <script type="text/javascri ...

The issue of the marker vanishing upon refreshing the page on AngularJS

Currently, I am encountering a rather peculiar issue. Upon the initial page load, the code snippet below correctly displays a marker at the specified coordinates and ensures the map is properly centered: <div class="paddingtop"> <map data-ng- ...

No content sent in the request body while implementing fetch

Attempting to send graphql calls from a React component to a PHP server using the fetch method for the first time. The setup involves React JS on the client-side and Symfony 4 on the server-side. Despite indications that data is being sent in the browser ...

Retrieve the website address from a string of HTML code

I'm struggling to extract the URL from a given String that contains an HTTP response with an HREF tag. I've managed to identify the start of the links, but I need to stop the string as soon as the HREF tag ends. How can I accomplish this? public ...

JSF automatically clears input fields during an ajax update

When inputting a name into the first billing first name field on my JSF page, I encounter an issue. If I select the copy billing address checkbox, it triggers an AJAX action that hides the delivery address panel. However, this also results in the value ent ...

The query encoding function of the NextJS router

Encountering an issue while trying to open a new page using NextJS router. The parameter was passed as follows: router.push({ pathname: '/', query: { id: '12344567' }, }) Occasionally, the page redirects to something like: /%3Fid ...

Tips for managing the onloadedmetadata event

If a video file cannot be played by the browser due to format or codec issues, I want to notify the user about it. When the browser is unable to play a video (because of unsupported format or codec), the onloadedmetadata event does not occur. I have some ...

What is the best way to perform calculations within a PHP loop for <input> elements and then display the results using a JavaScript loop?

Hello everyone, I'm currently struggling with displaying the calculations from a loop of input tags. What I'm trying to achieve is having 5 rows with input fields. At the end of each row, there should be a span area that displays the calculation ...

Utilizing ng-repeat $index for locating an element within an array

Within my $scope, there is a property called $scope.cars, which is an array of cars. Users have the ability to delete a car from this array. When calling the delete function deleteThis, I pass the $index parameter created by ng-repeat. However, in the Ja ...

Angular 4, Trouble: Unable to resolve parameters for StateObservable: (?)

I've been working on writing unit tests for one of my services but keep encountering an error: "Can't resolve all parameters for StateObservable: (?)". As a result, my test is failing. Can someone please help me identify and fix the issue? Here& ...

Using a comma format while typing in Angular ensures that the input field

When using jqxwidget from here, the default format includes commas separated by underscores. I am looking to have the field empty initially, with commas appearing as the user types - similar to a F2 cell renderer. For example, typing 100 should display a ...

Flexible Options in Drop-Down Menus

Is it possible to create a dynamic dropdown menu that displays the available quantity of products in stock? For example, if there are 45 products in stock, the dropdown should show numbers from 1 to 45. However, if 5 products have already been sold out, th ...

Extract a Key from a JSON Dictionary using Python

I've recently started working on a script as part of my practice routine. The purpose of the script is to take user input and then store it inside a Json file. Here's how the code looks: import json command = int(input("Do You Want To Add, Or Re ...

In Stripe.js, the background color and height of the credit card input cannot be customized

I'm struggling with customizing the appearance of a Stripe credit card input within my Vue.js application. I want to adjust the background color to #f1f1f1 and set the height to 60px, but despite trying both base styles and css, I can't seem to g ...

Tips for obtaining the sources of every image on a webpage and consolidating them in a single section

My goal is to preload all images on a webpage into a single division before the page loads. For example, if there are 5 images on the page (eg1.png, eg2.jpg, eg3.bmp, eg4.jpg, eg5.png), I want them to be contained within a div with the id 'pre'. ...

Tests are not visible to jasmine-node

Currently, I am utilizing jasmine-node and running it with the following command: node.exe path/to/jasmine_node --verbose path/to/my_file.js Despite successfully invoking Jasmine-node and receiving an error for incorrect paths, it appears that no tests a ...

Utilizing AngularJS to Extract JSON Data from Gzipped Files Stored Locally via Ajax

Currently, I am attempting to retrieve and read a JSON file that is stored in data.gz using AngularJS's $http service. However, when I make the request, all I get back are strange symbols and characters as the response. My application is being run loc ...

Trouble with Vuex Store: Changes to table values not reflected in store

I've been tackling a table project using Quasar framework's Q-Popup-edit and Vuex Store. The data populates correctly initially. However, any changes made on the table do not seem to persist and revert back to their original values. Here is a s ...

Issue with custom fonts not showing in PDFs when using Puppeteer, even though they are displayed in screenshots

I've been working on dynamically creating PDF files using the puppeteer library, but I'm facing an issue where the generated PDF doesn't display the custom fonts (.woff) that I have specified. Instead, it defaults to using the system font, T ...