Is this a good practice to handle normal and ajax calls with one controller:
<?php
class SomeController extends Controller {
function index() {
if(!$this->input->is_ajax_request()) {
// load model
// create form
// pass data to view
// ...
} else {
// validate input
// load model
// write data to database
// return with some json string
}
}
}
What are the advantages and disadvantages?
Short answer: it depends.
Only real difference between XHR (what marketing people call “AJAX”) and ordinary browser request is that XHR expects a different form of response.
In the MVC-inspired patterns for web the part that is responsible for generating response are the view instances. The view should recognize, which kind of response it has to produce, and act accordingly. Controllers role in this scenario would only be to change the state of current view.
Alternatively, you can, at the bootstrap stage, detect the
AcceptHTTP header, and based on that initialize a different view instance... but most of people do not use full MVC implementations.
If you are one of people, who, instead of MVC-inspired patters, uses Rails-like variation about page controller pattern, then you will be force to create a separate controller for handling XHR.
In this scenario the is no real view. It is replace by dumb template, while UI logic has been merged in the page controller. In this situation the only pragmatic option is to create a separate controller to deal with XHR.