Search code examples
javascriptjqueryajaxspring-bootthymeleaf

submit star-rating without redirection in thymeleaf and spring boot, using jquery, ajax


i am using star-rating jquery plugin in my project, here is the link https://plugins.krajee.com/star-rating#implementations. so, after clicking the stars, i would like to submit the result without redirection, with the help og ajax but i got error like Post http://localhost/rating/56 (id of project) 404 not found Here is my code

<form th:action="@{/rating/{id}(id=${projects.id})}" th:object="${rating}" method="post">
  <input  value="0" th:field="*{stars}"   hidden class="rating" data-glyphicon="0"
                                               id="stars">
</form>

ajax code is here

 $(document).ready(function() {
        var id=/*[[${projects.id}]]*/
        $('#stars').on('rating.change', function(event, value) {
            event.preventDefault();
            $.ajax({
                type: "post",
                contentType: "application/json",
                url: "/rating/" + id,
                data : JSON.stringify(id),
                dataType : 'json',
                dataType: 'json',
                success: function () {
                    console.log(id)
                }
            })
        });
    });

here is my spring controller

  @RequestMapping(value = "/rating", method = RequestMethod.POST)
@ResponseBody
public String rating(@RequestParam(value = "id") Long id, Model model, RatingModel ratingModel){
    try {
        projectService.save(ratingModel,  id);
    } catch (Exception e) {
        log.error("You have already rated");
    }
    return "redirect:/project/show-project/" + id;

}

As i know, in spring i should use @RestController to call ajax, but instead of that, here i added @ResponseBody annotation with @RequestParams, but i am confused why this implementation is not working

Please help


Solution

  • after spending a hours of solving a problem, i understood that the problem was in spring security, i mean, i added http.csrf().ignoringAntMatchers("/rating/**"). in my SecurityConfig class and my ajax worked, hope it will helps to someone, who will encounter with the same problem