AJAX interaction with PHP, using the ContextSwitch action helper

Well, when looking to simplify some actions and views that present JSON data to pass back from AJAX queries, I was pointed in the direction of the ContextSwitch action helper. One of the default contexts available, is the JSON context, which will disable all layout, and output serialized versions of any variables found in the view. This sounded perfect for what I wanted to achieve.

Basically, you tell the controller which additional contexts should be available in the init function of the controller, and then pass format=<context> to tell the action to render the page in that context. The code is:

public function init()
	$contextSwitch = $this->_helper->getHelper('contextSwitch');
	$contextSwitch->addActionContext('saverss, 'json')

You can then get anything set into a view variable json encoded by passing the querystring parameter format=json (or /format/json/), so:

public function saverssAction()
	$this->view->response = array('x', 'y', 'z');

Returns the JSON:


This is really helpful when you have a number of actions that are called using AJAX from your front-end. Thanks to Bittarman in the #zftalk channel for the heads up.

More Reading…

Your Comments are Awesome, Please Leave Them!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s