alli pierre yotti
alli pierre yotti

Reputation: 175

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" :"[email protected]",
              "usernameto" :"[email protected]"
           }

$.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

Upvotes: 2

Views: 4111

Answers (1)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10356

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" :"[email protected]",
            "usernameto" :"[email protected]"
        }

        $.ajax({
            type: "POST",
            url: "/emailsend?" + $.param(EmailData),
            dataType : 'json',
            contentType: 'application/json'
        });
});

Upvotes: 2

Related Questions