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

The cleanest way to deal with JSON form request

Ideneal
Ideneal
Jul 2 · 3 min read
  • Decoded JSON data
  • Fill the entity with data
  • Validate entity
  • Throw errors if there are some
  • If needed, you have to check the CSRF token separately into Controller’s action.
  • You need to render the form manually. So it means that the field’s names could mismatch from back-end (Hey don’t forget the CSRF token!).
{{ 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);
},
});
});