Dimness
Dimness

Reputation: 162

HTTP Error 415 when sending POST request with JSON data from HTML to Java Rest web service

I am trying to send the data from HTML form inside index.html to Java REST web service as a JSON data, using javascript and ajax. I tried whatever I found online so far, and still every time I get HTTP error 415.

I know the meaning of that error but can't figure out where I am wrong as I am not yet that much familiar with javascript.

Here is the code:

index.html

div style="text-align:center">
<form action="http://localhost/MyTaskTest/servicea" method="post" 
id="test">
<fieldset>
<legend>Add to Your balance</legend>
<label for="amount">Money amount</label>
<input type="text" name="Amount" /> <br/>
<label for="currency">Select currency</label>
<select name="Currency">
    <option value="eur">EUR</option>
</select>
<input type="submit" value="Add">
</fieldset>
</form>
</div>

<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
</script>
<script>

(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select" );
for( var i = 0; i < elements.length; ++i ) {
    var element = elements[i];
    var name = element.name;
    var value = element.value;

    if( name ) {
        obj[ name ] = value;
    }
}

return JSON.stringify( obj );
}


window.onload = function() {
var form = document.getElementById("test");
var output = document.getElementById("output");
form.onsubmit = function( e ) {
    e.preventDefault();
    var json = toJSONString( this );
            console.log(json);
            console.log("TEST");
    $.ajax({
        url: form.getAttribute( 'action' ),
        headers: { 
            'Accept': 'application/json',
            'Content-Type': "application/json; charset=utf-8"
        },
        type: 'POST',
        data: json,
        success: function(data) {
            alert("data saved")
            console.log("SUCCESS");
        },
        error: function() {
            console.log("ERROR");
            console.log(errorThrown);
        }
    })
};
}

})();

</script>

And here is the REST service:

@Path("/")
public class ServiceA {

    @POST
    @Path("/servicea")
    //@Consumes(MediaType.APPLICATION_JSON)
    public Response postRequest(String obj) {
        String res = "hii";
        return Response.status(200).entity(obj).build();
    }

EDIT

I edited my code...now it is working. but why do I need to set argument to String instead of JSONObject and remove @Consumes? In console I get this data from the variable that I send in ajax: {"Amount":"213","Currency":"eur"} ... So I am sending JSON,but service only works if argument is String.

FINAL EDIT

I managed to fix the problem, I was missing dependency for jersey-json. Thanks :)

Upvotes: 0

Views: 511

Answers (2)

Andrey
Andrey

Reputation: 549

There are some errors in your code, try to debug it in chrome developer tools. I have made some changes and it is works

    (function() {
    function toJSONString( form ) {
    var obj = {};
    var elements = form.querySelectorAll( "input, select" );
    for( var i = 0; i < elements.length; ++i ) {
        var element = elements[i];
        var name = element.name;
        var value = element.value;

        if( name ) {
            obj[ name ] = value;
        }
    }

    return JSON.stringify( obj );
}

window.onload = function() {
    var form = document.getElementById("test");
    var output = document.getElementById("output");
    form.onsubmit = function( e ) {
        e.preventDefault();
        var json = toJSONString( this );
                console.log(json);
        $.ajax({
            url: form.getAttribute( 'action' ),
            headers: { 
                'Accept': 'application/json',
                'Content-Type': "application/json; charset=utf-8"
            },
            type: 'POST',
            data: json,
            success: function(data) {
                alert("data saved")
            },
            error: function() {
                console.log(errorThrown);
            }
        })
    };
}

})();

Upvotes: 1

Adrian
Adrian

Reputation: 84

try to add

dataType: "json",
contentType : "application/json"

to your $.ajax method

$.ajax({
            url: $form.attr( 'action' ),
            dataType: "json",
            contentType : "application/json"
            type: 'POST',
            data: json,
            success: function(data) {
                alert("data saved")
            },
            error: function() {
                console.log(errorThrown);
            }
        })

also You had ; in your url field in $.ajax method - so better to remove it ;) Also its always better to check if service works corectly using for example PostMan so You are sure its not service side, I dont know what framework did You used, but You can also try to replace

public Response postRequest(JSONObject object) {

with

public Response postRequest(String object) {

to check if there is not a problem with mapping

Upvotes: 0

Related Questions