tags:

views:

110

answers:

3

I have a self-rolled MVC framework that I am building, and up to this point have managed to avoid the need for any AJAX calls. Now, however, I'd like to create a real-time updating feed.

My question is, where are the handlers for the ajax calls usually stored in an MVC? Should I store them in the same controller that is involved in making the call?

For example, if my domain www.example.com/browse/blogs (browse is the controller, blogs is the method) is making an AJAX call for an updated list of blogs, would the call simply be to www.example.com/browse/update_list or something?

OR, so it be to a separate AJAX-only controller? www.example.com/ajax/update_blogs

How do you do it?

A: 

Even though you're not using asp.net MVC, I'd recommend you look through the nerd dinner tutorial, specifically the AJAX section. it will help answer some of your design questions.

They have a separate action on the same controller.

http://tinyurl.com/aspnetmvc

No Refunds No Returns
+2  A: 

I'd say an Ajax request is exactly the same as a non-Ajax one : it works exactly the same way, actually, from a point of view of HTTP Protocol.

The only difference is that you are returning some non-formated data, as JSON or XML (hey, this is the same as generating an ATOM feed ^^ ), or only a portion of an HTML page.

So, I would treat those as any other "normal" HTTP request, and place them the way I would for non-Ajax requests.


A semi-alternate idea might be to have only one action in your controlller : /browse/blogs -- and always call that one.

But, it would detect if it's being via an Ajax request or not, and would :

  • return a full page if called via a "normal" request
  • or return only some data (or a portion of the page) if called via an Ajax request

Note : that's not a "wild" idea ; Zend Framework, for instance, provides some stuff to facilitate that (see 12.8.4.3. ContextSwitch and AjaxContext )

Pascal MARTIN
+2  A: 

Best practice would be to disregard the fact it's an AJAX request entirely and to only concern yourself with what controller your AJAX request is pertinent to. If you were to have a catch-all AJAX controller you'd likely be grouping apples to pears, so to speak.

The main difference is that for AJAX requests you will likely need to avoid setting any layout (and more than likely view) data. This can easily be remedied by having a method in your parent Controller class which checks for valid AJAX requests:

protected function isAjax()
{
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
            $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
}
cballou