Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send form data as a single JSON object?

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":"[email protected]"},{"name":"mobile","value":"99868377"}]

However, service only accepts the following JSON data
{ "firstName" : "John", "lastName" : "Miller", "email" : "[email protected]", "mobile" : "99868377" }

How to convert form data into a single JSON object instead of an array of JSON objects.

like image 243
Karthik Avatar asked Oct 29 '16 11:10

Karthik


People also ask

Can we send JSON in form data?

HTML provides no way to generate JSON from form data. If you really want to handle it from the client, then you would have to resort to using JavaScript to: gather your data from the form via DOM.

How do you store data from HTML form to JSON?

For this we are using json_encode() function which returns a JSON encoded string. We are making an array of values that the user fills in the HTML form. Then we pass this array into json_encode() function. Then json_encode() function returns a JSON encoded string.

What is a single JSON object?

A JSON object contains zero, one, or more key-value pairs, also called properties. The object is surrounded by curly braces {} . Every key-value pair is separated by a comma. The order of the key-value pair is irrelevant. A key-value pair consists of a key and a value, separated by a colon ( : ).


1 Answers

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;
}
like image 117
Karthik Avatar answered Nov 15 '22 09:11

Karthik