I have an html form, a button and a click handler to manage the submission of the form. Question is specifically about the handler of the button to submit the form via AJAX.
This is the handler I wrote:
JS:
$('#create').click(function(event) {
console.log('Create Button Click');
var dataJSON = JSON.stringify( $('#customer_form').serializeArray() );
console.log(dataJSON);
$.ajax({
type: "POST",
url: "/customer/",
// The key needs to match your method's input parameter (case-sensitive).
data: dataJSON,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log('Success');
console.log(data);
},
failure: function(errMsg) {
console.log('Error');
console.log(errMsg);
}
});
event.preventDefault();
});
I have used JSON.stringify( $('#customer_form').serializeArray() );
to generate the JSON string, getting as result -as shown by console.log(dataJSON)
:
[{"name":"name","value":"n"},{"name":"address_line_1","value":"a1"},{"name":"address_line_2","value":"a2"},{"name":"town","value":"t"},{"name":"postal_code","value":"p"},{"name":"region","value":"r"},{"name":"phone_1","value":"p"},{"name":"phone_2","value":"pa"},{"name":"fax","value":"f"},{"name":"email","value":"e"},{"name":"web","value":"w"}]
Which would be the easiest way to get the following structure:
[{"name": "n", "address_line_1": "a1", "address_line_2": "a2", "town": "t", "postal_code": "p", "region": "r", "phone_1": "p", "phone_2": "pa", "fax": "f", "email":"e", "web": "w"}]