MVC: how to ajax? MVC: how to ajax? ajax ajax

MVC: how to ajax?


You really should read the manual chapter about ContextSwitch Action Helper. But here is a brief outline:

  • your view scripts (action-name.phtml) are used for regular HTML output
  • you can initialize a context switch for some actions in the controller so thay can output for example XML - xml context is supported by default and you would put your view script for xml context in (action-name.xml.phtml); xml context also disables rendering of the layout
  • json is also supported by the built in context switch and default option is to disable both the layout and the view and to output all the variables assigned to the view from the controller action in JSON format, this option can be toggled by using the setAutoJsonSerialization(false) method of the context switch; but if you switch it you have to create a view script action-name.json.phtml and output the variables in JSON format by hand

To switch between these two contexts you have to add a format parameter to your URL, e.g. /posts/author/ivan/format/json or /posts/author/ivan/format/xml. If you do not specify the format your application will output plain html.

Special version of the Context switch is AjaxContext and you also have to configure this one by hand. It does not use the 'format' parameter to identify which format it should use for output but it examines the header sent in your request and looks for 'X-Requested-With: XmlHttpRequest' header and if it is present the AjaxContext is examined. Using the AjaxContext action helper you can specify which context should be used for specific actions if the request is fired using AJAX.


You can utilize the same actions to return XML, JSON or whatever, by detecting ajax requests and thus being able to differentiate ajax requests from normal ones. For example:

public function fooAction(){    if($this->getRequest->isXmlHttpRequest()) {        echo json_encode($someData);    } else {        echo 'This is the normal output';    }}


Your View can be something other than HTML, and either the pipeline can react to the request being an ajax post, or your controller can react. Either way, it should be as simple as return a different View.