Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to structure AJAX for a Zend Framework application

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.

like image 295
John Nall Avatar asked May 28 '10 01:05

John Nall


2 Answers

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

like image 171
karim79 Avatar answered Sep 29 '22 02:09

karim79


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.

like image 34
Andy Baird Avatar answered Sep 29 '22 01:09

Andy Baird