Search code examples
javascriptajaxspring-bootspring-restcontroller

How to pass Parameter from Ajax to RestController in Spring Boot


i try to pass Parameter from Ajax to RestController to send a Email.

That is the Controller Post Methode to send the Enail

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String create(@RequestParam("covere") String covere, @RequestParam("title") String title,
            @RequestParam("username") String username, @RequestParam("usernameto") String usernameto) {
        try {
            mailService.sendMail(covere, title, username, usernameto);
            return "sendmail";
        } catch (MailException e) {
            e.printStackTrace();
        }
        return "sendmail";
    }

That is the Ajax to Call the Post and pass the Variable to send Message

$("#vuta").on("click", function(e) {
    var EmailData = {
              "covere" : "John",
              "title" :"Boston",
              "username" :"test@yahoo.fr",
              "usernameto" :"test@yahoo.fr"
           }

$.ajax({
    type: "POST",
    url: "/emailsend",
    dataType : 'json',
    contentType: 'application/json',
    data: JSON.stringify(EmailData)
});
});

I have this Error when i send the Email

Required String parameter 'covere' is not present","path":"/emailsend"}

Thank for help


Solution

  • Your controller is expecting parameters via Query String. You can use $.param to format the object as query string and send it in the URL:

    $("#vuta").on("click", function(e) {
            var EmailData = {
                "covere" : "John",
                "title" :"Boston",
                "username" :"test@yahoo.fr",
                "usernameto" :"test@yahoo.fr"
            }
    
            $.ajax({
                type: "POST",
                url: "/emailsend?" + $.param(EmailData),
                dataType : 'json',
                contentType: 'application/json'
            });
    });