How to handle JSON requests using forms on Symfony 4 and getting a clean code

The cleanest way to deal with JSON form request

{{ form(form) }}
(function ($) {
$.fn.serializeFormJSON = function() {
let o = {};
let a = this.serializeArray();
$.each(a, function () {
let name = this.name;
let value = this.value || '';
if (o[name]) {
if (!Array.isArray(o[name])) {
o[name] = [o[name]];
}
o[name].push(value);
} else {
o[name] = value;
}
});
return o;
};
})(jQuery);
$('form').submit(function(e) {
e.preventDefault();

let form = $(this);
let url = form.attr('action');
let data = form.serializeFormJSON();
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
console.log(data);
},
});
});

Full-stack Developer & Security Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store