Responding to Ajax Requests

The typical way to respond to an Ajax request is to send back JSON-encoded data. You can do this easily by calling the $this->sendJson() method.

This method accepts as its only argument the data you would like encoded as JSON data.

The following listing demonstrates this functionality. It returns JSON data in all cases (regardless of whether the request was an Ajax request or not).

Example 5.1. Return JSON data from a request (driver.php)

<?php
    class Driver_backend_requests_weather_controller extends Module_Backend_Driver_Abstract
    {
        public function getDependentModules()
        {
            return array('weather');
        }
        
        public function indexAction($path)
        {
            $request = $this->getPost();
            $city    = $request->getPost('city');
            
            $weather = array(
                'city' => $city,
                'temp' => '35 Celsius'
            );
            
            $this->sendJson($weather);
        }
    }
?>

In some cases you may want to send JSON-encoded data only if the request was an Ajax request. This is useful when making your web site degrade gracefully for browsers that don't support JavaScript.

You can check the isXmlHttpRequest() method on the request to check for this.

Example 5.2. Return JSON data only for Ajax requests (driver.php)

<?php
    class Driver_backend_requests_weather_controller extends Module_Backend_Driver_Abstract
    {
        public function getDependentModules()
        {
            return array('weather');
        }
        
        public function indexAction($path)
        {
            $request = $this->getPost();
            $city    = $request->getPost('city');
            
            $weather = array(
                'city' => $city,
                'temp' => '35 Celsius'
            );
            
            if ($request->isXmlHttpRequest()) {
                $this->sendJson($weather);
            }
            else {
                // don't do anything - the user will be returned
            }
        }
    }
?>