0

I'm programming a commentary box for a Web Client.

I have two tables, one for the Comments and one for the Users. I want to send Input Data from my <input> tags in HTML form to my Java Service. In this Service, I handle the received data. My Problem now is, that I get an HTTP-415 error and I don't know what to do Right now.

I am using AJAX in JavaScript to post 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("FAILIURE");
        }
    });


});} 

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...
}
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
Touko
  • 31
  • 1
  • 6
  • Possible duplicate of: https://stackoverflow.com/q/22566433/3991696 – vishwarajanand Jun 18 '18 at 10:57
  • You have used `$("#author")` but `author` is name of your input tag instead of id. Also, can you try with adding `Content-Type` in Ajax call? – Kiran Jun 18 '18 at 11:11
  • Error code [415](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415) means that you haven't specified a valid/supported media type, ex: html or json. You might want to take a look at [this](https://benjamin-schweizer.de/jquerypostjson.html). – Olian04 Jun 18 '18 at 11:18

1 Answers1

0

jQuery's default content type for the Ajax function is 'application/x-www-form-urlencoded; charset=UTF-8'. Because the service is expecting 'text/plain' the content type needs changed.

Add a content type:

data: post,
contentType: 'text/plain',  //<--- insert
success: function(){
G Cadogan
  • 183
  • 1
  • 9