Making Ajax calls is a trivial task nowadays for any web developer, and I’m sure it’s no enigma for all of you how to do it using your favourite Javascript library or framework like jQuery, Angular, Backbone, you name it.

 

But how do we handle these requests in the backend? More specifically, how should we write our controllers to take full advantage of our preferred framework, Symfony 2 in my case, and create a great UX for our consumers (with errors displayed nicely and effortless) and a great feeling for our colleagues with whom we share the code (by using status codes and promises).

Firstly I prepare a basic controller, while trying to respect REST principles. This will prove very valuable later on in the project and your app flow will be easier to follow. A good article on that can be found here .

/Acme/DemoBundle/Controller/DemoController.php

Then I prepare my HTML:

/Acme/DemoBundle/Resources/Demo/new.html.twig

And then I build the form; It’s always a good practice to put the fields of your form in a separate file so that you can reuse them for the edit form for example.

/Acme/DemoBundle/Resources/Demo/form.html.twig

And to tie the frontend with the backend we add a little Javascript (JQuery flavoured). This code simply listens to all submits from the page, and if the submitted form has the class ajaxForm then it submits it using Ajax.

 

Thanks to the handy promises .done and .fail, and to the use of status codes in our response (400  -> Bad request, 200 -> Ok, 404 -> Not Found and so on) the script will automatically go to the right promise and will make handling the response a lot easier. Also, if an error occurs in your form (e.g. a field is invalid), then the form is re-rendered with the errors displayed.

 

/Acme/DemoBundle/Resources/public/main.js

 

Going a little further, you could put this form in a modal (easily done with bootstrap) and you can get a really nice user interface with forms in modals submitted with Ajax.

Last but not least, don’t forget to check that your routings are correct in case you didn’t do it already:

app/config/routing.yml

 

Have fun coding 🙂

Privacy Preference Center