I thought of having an AJAX module service layer, with controllers and actions that interact with my model. Easy, but not very extensible and would violate DRY. If I change the logistics of some process I'll have to edit the AJAX controllers and the normal controllers.
So ideally I would load the exact same actions for both javascript and non-javascript users. I have thought about maybe checking for $_POST['ajax']
, if it is set I would load a different (json'y) view for the data. Was wondering how/a good way to do this (front controller plugin I imagine?) or if someone can point me to an UP TO DATE tutorial that describes a really good way for building a larger ajax application.
You can actually use the request object to determine if a request has happened through ajax, e.g.:
// from your controller
if($this->getRequest()->isXmlHttpRequest()) {
// an ajax request, do something special (e.g. render partial view)
} else {
// render entire view
}
That's basically testing for the x-requested-with
header (which is not always present, depending on JS library, etc). See (under the heading of 'detecting ajax requests'):
http://framework.zend.com/manual/en/zend.controller.request.html
You can check for XmlHttpRequest headers. Not all Javascript libraries do this, though, and even the ones that do don't necessarily do it in all browsers.
There's also AjaxContext, which basically checks the "context" request variable similar to your idea of $_POST['ajax'].
What I actually ended up doing was similar to your original suggestion. I created an AJAX module. In order to prevent tons of controller code duplication, I created a service layer that handles all the operations on models, so my controllers are really only responsible for transforming input requests and display.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With