Tag Archives: encode()

Returning JSON in a Zend Controller’s Action

There are three basic ways that you can achieve that. First of all what’s the task? You’ve an array, either from a database result or whatever, and you encode it JSON with Zend_Json::encode($array)

// IndexController.php
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$data = array(...);
 
		$this->view->data = Zend_Json::encode($data);	
	}	
}

The result in general is a specially formatted string. So you can simply set it up to a view member variable and pass it to the view.

// index/index.phtml
echo $this->data

In that case you’ve a .phtml file to maintain, so lets just return the string and “setNoRender” the view in our second try.

// IndexController.php
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$data = array(...);
 
		echo Zend_Json::encode($data);	
 
		$this->_helper->viewRenderer->setNoRender(true);
	}	
}

Actually this is pretty much the most clear solution, but actually you can output the JSON string and simply exit() as it’s shown in our third example.

// IndexController.php
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$data = array(...);
 
		echo Zend_Json::encode($data);	
 
		exit();
	}	
}

Which one is to be used is up to the developer’s choice, mine is the third one as it’s the minimal one.

JavaScript encode cyrillic symbols with encodeURIComponent

JavaScript and Cyrillic

Let’s assume we’ve a JavaScript file which rewrites the location.href, resulting in changes in the URI of the browser. Everything is OK till you work with Latin alphabet. The problem arises when you decide to put some Cyrillic symbols into the string.

The encode() function

With that function you can encode the URL if you have some entity symbols. It is not like but it should be something like encodeURI in PHP. The problem is that this function does not work correctly with Cyrillic symbols.

Use encodeURIComponent

There is another usefull function which does this. It’s called encodeURIComponent, and I strongly recomment its use.