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

The cleanest way to deal with JSON form request

Most of times we are dealing with Ajax forms, so we need to manipulate JSON data and send it to the server. There are several ways to handle JSON requests and validate data.

I’ve seen many developers using the Validator component and their process was the following:

  • Create an entity with related annotations
  • Decoded JSON data
  • Fill the entity with data
  • Validate entity
  • Throw errors if there are some

But this approach has such limits like the following:

  • You must create an entity class for each JSON data you would validate (YES, even if it has only one field!)
  • 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!).

Luckily there is a faster and reliable way to do that. Symfony provides the Form component which we can use also to handle JSON data. To do that we need of just one single form method: submit…That’s it!

Using the Form component you follow the almost same previous process but without the related limits, moreover you have all necessary tools to render the form into a Twig template.

Supposing you have to deal with a recovery password process and you have a form which has one single input email…the following will be the result:

On the Twig template recovery.html.twig you will render the form simply by typing the following:

{{ form(form) }}

Now you must serialize JSON data in order to use it afterwards. Using jQuery you could extend its behaviour by adding the following function within a script tag:

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

Finally you can now bind form submit and send the JSON data to our endpoint:

$('form').submit(function(e) {

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

That’s it! 😉

Oh! If you have noticed the FormException within the controller and you are asking “How could I manage the form errors in such a way as to reply a correct JSON with each field errors?” you could read my previous article Symfony 4 — A good way to deal with exceptions for REST API 😉

I hope this article has given you a suggestion to handle your forms for your work or personal project! Let me know what do you think about it! 😃

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