I am developing an application in Kohana framework. I would like to know the best practices in implementing ajax in kohana. So far I am using different controller for ajax. I think the important concerns will be minimizing the resources requirement and handling sessions.
Thanks in advance
I'm using this:
In Controller_Template:
public function before()
{
$this->auto_render = ! $this->request->is_ajax();
if($this->auto_render === TRUE)
{
parent::before();
}
}
And inside my actions:
if ($this->request->is_ajax())
{
...
$this->response->headers('Content-type','application/json; charset='.Kohana::$charset);
$this->response->body($jsonEncoded);
}
As the fellas above said, you don't need a separate controller for your ajax actions. You may take advantage of Kohana's request object to identify the request type. This may be done in the following way:
<?php
class Controller_Test extends Controller_Template {
/**
* @var View Template container
*/
protected $template = 'template';
/**
* @var View Content to render
*/
protected $content = 'some/content/view';
// Inherited from parent class
protected $auto_template_render = TRUE;
public function before()
{
parent::before();
if ($this->request->is_ajax() OR !$this->request->is_initial()) {
$this->auto_template_render = FALSE;
}
}
public function after()
{
if ($this->auto_template_render == FALSE) {
// We have ajax or internal request here
$this->template = $this->content;
} else {
// We have regular http request for a page
$this->template = View::factory($this->template)
->set('content', $this->content);
}
// Call parent method
parent::after();
}
}
Though the example is very simple it may be improved to what you want to archive. Basically I've finished up writing my own Controller_Template
to do the stuff I need. Also you may consider adding the format parameter to your urls so that the .html
urls returned the regular html representation of the data and .json
urls did the same, but in json format.
For more information (and probably ideas) see kerkness unofficial Kohana wiki
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With