MVC using jQuery

 A new model for web forms

The traditional web model

The usual route of forms is along the lines of:

  • Browser requests page
  • Apache/PHP generates page with data embedded in form elements
  • User fills in form, clicks submit
  • Browser sends POST
  • Apache/PHP processes form data, generates another page

The biggest chore is populating the form data in PHP. The model and the view are combined, and the controller is very much server-side, often strewn throughout the view generation!

Client side MVC

Taking inspiration from XForms, and using jQuery we can separate the efforts, so that we no longer need to perform the tedious job of populating forms in PHP.

The model is supplied in JSON, the view is just plain XHTML with custom attributes on the form elements to indicate bindings to the model, and the controller is just Javascript.

  • Browser requests page
  • Apache returns a view (HTML page, possibly static) and a controller (Javascript)
  • The controller retreives the model (via an XMLHttpRequest, or embedded within the view)
  • Apache/PHP builds the model and serializes it to JSON
  • The controller binds the model to the view (form elements etc.)
  • User interacts with the view (fills in form)
  • The model is updated from changes to the view as they happen
  • User clicks submit
  • The controller serializes the model back to JSON and sends it via an XMLHttpRequest
  • Apache/PHP unserializes and processes the model, returning another model (may or may not be the same type of model)
  • The controller checks the response and acts accordingly

Here we have a complete separation:

  • Model: JSON data generated and processed by PHP.
  • View: Purely static XHTML with a some custom attributes (after all thats what XHTML is for).
  • Controller: Javascript that binds the Model and View together.

jQuery MVC plugin

I've developed a jQuery MVC plugin that allows you to bind model values to a view element or a function. So when the value of the element changes the model value is updated. In turn an update to a model value triggers any bound functions to be called and any bound elements to be updated.

Have a look at the examples below. I'll try to add more if I get time.

If you have any comments or suggestions feel free to email me: jollytoad (at) gmail (dot) com