Ajaxify a Form with Backbone
I have been working a lot with Yeoman lately and find it to be absolutely fabulous. It’s make web development a real joy. With a few simple commands I can have a Backbone, Require.js and Twitter Bootstrap application ready. Also, instead to manually searching and downloading a JavaScript library it is so refreshing to run “bower install —save jquery-form” and you are done.
Anyways, in this short blog, I want to share a neat trick that I adopted to submit forms via AJAX in a web application. We will be using a few libraries for this most important of which is the jquery form plugin which enables us to submit forms via AJAX.
I have a form lets say, which I want to AJAXify -
Normally the flow looks like the images below -
Now with the help of a little bit of Backbone and jQuery Form plugin I can easily turn this into an AJAX enabled form -
Let me explain the code, behind the scenes we have initialized our Backbone View shown above and binded the “handleSubmit” function to the form submit event.
The handleSubmit function checks if the form has the “data-ajax” attribute and using the jQuery form plugin’s API submits the form via AJAX.
The server side code can look something like -
The advantage of this approach is that the application will work even if JavaScript is disabled and also we can easily turn off AJAX by setting the “data-ajax” attribute to false in HTML, no JavaScript needs to change anywhere.
That’s it, using this simple method you can AJAXify your forms easily.
- Code is available on Github.