0

When I try to send a list with ajax to a method in spring controller I get this error:

Content type 'application/x-www-form-urlencoded' not supported

my AJAX code:

$('#btn-save').click(
    ajaxSend();
);

function ajaxSend() {
    $.ajax({
        url: "/kepres2Web/mvc/spatiu/update",
        type: 'POST',
        dataType: 'json',
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(rects),
        success: function (data) {},
        error: function (data, status, er) {},
        headers: {
            'Content-type': 'application/x-www-form-urlencoded'
        }
    });
}

my method:

@RequestMapping(value = "/update", method = RequestMethod.POST, produces = {"application/json", "application/xml"}, consumes = {"application/x-www-form-urlencoded"})
public String update(@ModelAttribute("record") Spatiu spatiu,@RequestBody List<Desk> deskList) {
    System.out.println(deskList.get(0).getFill());

    dao.update(spatiu);
    //return null;
    return "redirect:view?ls&id=" + spatiu.getId();
}

and my button:

<button id="btn-save" type="submit" form="frmDetails" formaction="update">
    <img src="${pageContext.request.contextPath}/img/actions/save.png">
    <br>Salvare
</button>

EDIT

Found out that Spring doesn't understand application/x-www-form-urlencoded as RequestBody so I removed it and added @ResponseBody on method. Now it returns and empty list.

Rob
  • 2,243
  • 4
  • 29
  • 40
Dan
  • 63
  • 1
  • 7
  • you're setting the content type twice - once in the `contentType` option and once in the `headers` option, and you're setting it to two different values. – ADyson Oct 23 '17 at 08:35
  • Also see https://stackoverflow.com/questions/33796218/content-type-application-x-www-form-urlencodedcharset-utf-8-not-supported-for for a possible solution to the message. – ADyson Oct 23 '17 at 08:37
  • Removed headers. Still not working @ADyson. Same error – Dan Oct 23 '17 at 08:48
  • add consumes as application json. You only have produces. – ScanQR Oct 24 '17 at 12:01

1 Answers1

0

Couple of things to fix in your code.

  1. You have defined headers 2 times. Headers defined by headers takes precedence. You need to remove that to be able to send json data your service.

  2. On @RequestMapping you need to define consumes in order to accept the data as json. Check if you have by default json as accepted data otherwise configure explicitly using consumes.

@RequestMapping(value = "URL", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)

ScanQR
  • 3,740
  • 1
  • 13
  • 30