PHP: AJAX and the MVC pattern

If you run a search for AJAX and the MVC pattern, you'll surely notice that the overwhelming majority of results explain you how to create an AJAX-based MVC system but not how to integrate AJAX into an existing one. AJAX is already a three-component system, being based on the interaction between browsers, JavaScript and a web server. The problem with AJAX is that we actually don't know where to put it within an MVC pattern. Do we need an AJAX Model? Do we need an AJAX Controller? Do we need an AJAX View? Since AJAX works in the web browser, and the web browser handles only the View part of our design pattern, it seems obvious that we only need an AJAX View. In other words, we only need that our components return an output that can be handled by JavaScript and AJAX. But here a problem arises: what if our HTML template system is not set to handle such situations?

Either if you use a custom template system or a pre-built one (such as Smarty), you have to determine what kind of response you should return. AJAX can handle HTML, XML, plain text, JavaScript and JSON, among the others. If your template system is already designed to return mostly HTML, you can choose to return simple HTML snippets. Done that, there's another problem: how to handle an AJAX request? Or, more clearly, how to determine when the request we're receiving is an AJAX request?

Facebook seems to have addressed this problem brilliantly: an AJAX component has been created within the system to handle all the AJAX requests. If you follow the traditional MVC approach and all your requests are routed to the main index.php file, then you have two options:

  1. use a robust framework to handle AJAX requests (e.g. Zend)
  2. implement a custom system to detect and process AJAX requests.

AJAX requests are normal HTTP requests, either GET or POST. JavaScript needs a URL where the request can be sent and it expects a response. URLs are exactly in the same format of all other dynamic URLS, for example http://example.com/?view=user&id=10, so you don't have to worry too much about this. All you need to do is to tell to your client-side developer(s) to redirect all AJAX calls to the main index.php file. Your .htaccess settings and your MVC system will do the rest. Bear in mind that JavaScript handles AJAX by following a three-step process:

  1. send the request
  2. receive the response
  3. process/display the response.

For debugging purposes, it's better to work with normal requests first. You should add AJAX only when you're sure that a given URL will be interpreted correctly, processed correctly and that it will return a proper and meaningful response. For example, if your PHP code returns a MySQL error, AJAX won't show anything in most cases, so you need first to check out whether your code is correct or not.

This entry was posted in , by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.