I have a web page built with Bootstrap and jQuery.
A modal dialog box displays a simple form. On button click, it posts the form contents as JSON to my REST web service.
Here’s the modal dialog …
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Create New User</h4>
</div>
<div class="modal-body">
<form id="createForm">
<p><input id="firstName" type="text"/>
<p><input id="lastName" type="text"/>
<p><input id="emailAddr" type="text"/>
<button id = "doCreateButton" class="btn btn-primary" type="submit">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
Here’s the script that does the POST …
<script>
$(function() {
//twitter bootstrap script
$("#doCreateButton").click(function() {
$.ajax({
type : "POST",
url : "http://localhost:8080/myapp/json/user/create",
data : JSON.stringify( $('#createForm').serialize()),
success : function(msg) {
$("myModal").modal('hide');
},
error : function() {
alert("failure");
},
done : function(e) {
console.log("DONE");
$("myModal").modal('hide');
}
});
});
});
</script>
The problem, is the text that gets sent to the REST web service is this …
%22%22=
What am I doing wrong?
UPDATE:
Here’s a snippet of from the backend, a REST service built with Spring Web @RestController …
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/.../
@RestController
public class WebRestController {
@Autowired
UserService userService;
public WebRestController() {
// TODO Auto-generated constructor stub
}
@RequestMapping(value = "/json/user/create", method = RequestMethod.POST)
public ResponseEntity<String> createUser(@RequestBody String json) throws Exception {
/* ... do stuff ... */
return new ResponseEntity<String>(replyObj.toJSONString(), HttpStatus.OK);
}
3
Answers
You can try this.
Firstly,
JSON.stringify( $('#createForm').serialize());
returnsYou can send data
JSON
like this:jsonData variable is now json
Here is the Ajax Request.
Finally, on the Server side, you should catch the
@RequestBody UserRequest userRequest
by creating request dto class like below.Thanks for the help everyone. In the end, I got it working like this: