ygrunin
ygrunin

Reputation: 345

ajax POST request in spring boot app

I am trying to perform an action on server without navigation or refreshing the page. As i understand i need to use AJAX call. I have tried two approaches but getting problems.

Controller version 1:

@RequestMapping(value = "/vote", params = {"match","player", "voteValue"}, method  = RequestMethod.POST)

                public  @ResponseBody String voteup(@RequestParam("match") int match, @RequestParam("player") int player,  @RequestParam("voteValue") int voteValue){

                voteService.save(match, player, voteValue);
                String returnText = "Vote has been recorded to the list";
                return returnText;

                }

Controller version 2:

@RequestMapping(value = "/vote", method  = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public  String voteup( @RequestBody Vote vote  ){
        vote.getMatch();

                //voteService.save(match, player, voteValue);
            String returnText = "Vote has been recorded to the list";
            return returnText;
    }   

JSP:

<c:if test = "${not empty matchform.lineup }">
                                 <c:forEach var="lineup" items="${matchform.lineup}">

                                    <c:if test = "${lineup.team.apiTeamId eq matchform.homeTeam.apiTeamId}">
                                    <hr>${lineup.player_name}  -  ${lineup.position}
                                          <form action="/vote" method=post  id = vote-form> 
                                                <button class="btn btn-xs btn-primary btn-block" type="submit" >Vote Up</button> 
                                                <input type="hidden" id = match name="match" value="${lineup.matchId.id}" />
                                                <input type="hidden" id = player name="player" value="${lineup.player.id}" />
                                                <input type="hidden" id = voteValue name="voteValue" value="1" />                                           
                                            </form> 
                                             <form action="/vote" method=post id = vote-form1>  
                                                <button class="btn btn-xs btn-primary btn-block" type="submit" >Vote down</button> 
                                                <input type="hidden" name="match" value="${lineup.matchId.id}" />
                                                <input type="hidden" name="player" value="${lineup.player.id}" />
                                                <input type="hidden" name="voteValue" value="0" />                                          
                                            </form> 
                                    </c:if>             
                                 </c:forEach>               
                            </c:if>

... and the js

jQuery(document).ready(function($) {
        $("#vote-form").submit(function(event) {

            // Prevent the form from submitting via the browser.
            event.preventDefault();
            voteViaAjax();

        });
    });

    jQuery(document).ready(function($) {
        $("#vote-form1").submit(function(event) {

            // Prevent the form from submitting via the browser.
            event.preventDefault();
            voteViaAjax();

        });
    });


    function voteViaAjax() {

        var match = $('#match').val();
        var player = $('#player').val();
        var voteValue = $('#voteValue').val();
        var vote = {"player" : player, "match" : match,  "voteValue": voteValue};


        var token = $("meta[name='_csrf']").attr("content");
        var header = $("meta[name='_csrf_header']").attr("content");

        $.ajax({
            type : "POST",
            contentType : "application/json",
            beforeSend: function(xhr) {
                xhr.setRequestHeader(header, token)
              },
            url : "/vote",  
            data : JSON.stringify(vote),
            dataType : 'json',
            timeout : 100000,
            success : function(data) {
                console.log("SUCCESS: ", data);
                $('#info').html(data);
            },
            error : function(e) {
                console.log("ERROR: ", e);

            },
            done : function(e) {
                console.log("DONE");
            }
        });
    }

The problem with version 1 of controller i am getting the error :

""status":400,"error":"Bad Request","exception":"org.springframework.web.bind.UnsatisfiedServletRequestParameterException","message":"Parameter conditions \"match, player, voteValue\" not met for actual request parameters:"

The second controller i cant use because my Match and Player are object , and i found only how to send the String values as part of the Vote object.

Thank you all in advance!!!!!

Upvotes: 0

Views: 8552

Answers (1)

Klaus Groenbaek
Klaus Groenbaek

Reputation: 5035

You need a mix of the two controllers.

The controller method needs to have @ResponseBody, so the response is serialized, and maybe you want to send back an object not a string. In Spring if a controller returns a String without @ResponseBody then the String identifies the "View" to forward to.

Your JavaScript is sending a JSON object so you should have @RequestBody, like controller 2.

If your Controller is only used for Rest endpoints, you should consider using the @RestController annotation, it automatically adds @RequestBody, @ResponseBody, and produce/consume semantics to your controller methods.

I'm much better at Java than JavaScript, so I typically test my service using PostMan, or write a test. Once I know how the Json should look, I write the JavaScript, if I get an error back I check what the browser sent using developer tools.

Personally I have written a lot of JSP applications during the last 13 years. I'm not a front end developer, but during the last 2 years I have built a number of internal application to help our development team. Today I would choose Angular(JS) for any application that needs ajax capabilities (the only server side logic is getting you spring model into JS variables). If I need to build an app that uses serverside rendering I would not use JSP, I would use Tymeleaf.

Upvotes: 1

Related Questions