How to send form data as a single JSON object?
form-submit, jquery, json, spring-mvc
Solution
I finally found a solution. I have written an utility method which generates JSON object
$(document).ready(function(){
var contextroot = "/services/"
$("#customerForm").submit(function(e){
e.preventDefault();
var form = $(this);
var action = form.attr("action");
var data = form.serializeArray();
$.ajax({
url: contextroot+action,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(getFormData(data)),
success: function(data){
console.log("DATA POSTED SUCCESSFULLY"+data);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
});
//utility function
function getFormData(data) {
var unindexed_array = data;
var indexed_array = {};
$.map(unindexed_array, function(n, i) {
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
Problem
Below is my code(client) to send form data in JSON format via JQUERY Ajax call ``` $(document).ready(function(){ var contextroot = "/services/" $("#customerForm").submit(function(e){ e.preventDefault(); var form = $(this); var action = form.attr("action"); var data = form.serializeArray(); $.ajax({ url: contextroot+action, dataType: 'json', type: 'POST', contentType: 'application/json', data: JSON.stringify(data), success: function(data){ console.log("DATA POSTED SUCCESSFULLY"+data); }, error: function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown ); } }); }); }); ``` Below is the SPRING controller(service) to accept JSON data ``` @RequestMapping(value="/customer/create", method = RequestMethod.POST) public CustomerDTO create(@RequestBody CustomerDTO customerDTO) { return customerService.create(customerDTO); } ``` On submitting the form, I get the following error HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax. I guess this error is because the form data is serialized as array of JSON objects instead of just JSON object in request body as shown below [{"name":"firstName","value":"John"},{"name":"lastName","value":"Miller"},{"name":"email","value":"John@gmail.com"},{"name":"mobile","value":"99868377"}] However, service only accepts the following JSON data { "firstName" : "John", "lastName" : "Miller", "email" : "John.kp@gmail.com", "mobile" : "99868377" } How to convert form data into a single JSON object instead of an array of JSON objects.