DistribuzioneGaussiana DistribuzioneGaussiana - 5 months ago 18
Ajax Question

Ajax function with Jquery returns 400 error

I'm using

Jquery
with
Spring MVC
.

I have an
index.jsp
:

<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous">

</script>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
<script type="text/javascript">
</script>
<script>
$(document).ready(function() {
$("input").keyup(function() {
$.ajax({
url : "myController",
type: "POST",
data: $("#name").val(),
success : function(result) {

alert(result);
}

});
});
});
</script>

</head>

<body>

<form>
<div class="row">
<div class="col-sm-12">
<label for="name">Name:</label>
</div>
<div class="col-sm-1">
<input type="text" class="form-name" id="name" placeholder="Paolo">
</div>
</div>
</form>
</body>
</html>


As you can see when one inserts a letter in the input box I run
$ajax
with jQuery.
My HTTP POST request is correclty sent but I have a 400 error.

This is my simple Controller class:

@Controller
public class MyController {


@RequestMapping(value="/myController", method = RequestMethod.POST)

@ResponseBody
public String getData(@RequestParam(value="name") String name) {

return name;
}
}


My DispatcherServlet for Spring MVC is correclty setted.
How can I solve?

Answer

A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules.

Your ajax call would be

$.ajax({
        url : "myController",
        type: "POST",
        data:{"name": $("#name").val()},
        success : function(result) {                       
                 alert(result);
               }

       });