refactoring? my controllers to work with ajax requests
Posted: Thu Mar 22, 2007 3:53 pm
I have an application that I want to ajaxify™. I am wondering what the best way to go about this would be. I was thinking of taking my existing actions and depending on whether or not a param called ajax was set, I would return a json response, otherwise, I'd just do the normal thing. Here is an example action:
Now, I was thinking that in my Application Controller, I'd detect if the ajax parameter was set and if so, set $this->_ajax to true, and then doing something like:
Is this a good idea? How would you guys go about it?
Code: Select all
public function addAction()
{
if (!$this->_isLoggedIn()) return; // make sure user is logged in
$project = $this->_session->Project;
$action = 'question';
if ($pos = $this->_processId($this->_post->getRaw('question_id')))
{
$project->goto($pos);
$action = 'review'; // change where we're forwarding
}
$answer = $this->_validateAnswer();
$project->addAnswer($answer);
/**
* If there were any issues with adding the answer, _validateAnswer
* will have already taken care of the error messages, etc. so
* it is safe to simply forward the user to the question action now
*/
$this->_forward('project', $action);
return;
}Code: Select all
public function addAction()
{
if (!$this->_isLoggedIn()) return; // make sure user is logged in
$project = $this->_session->Project;
$action = 'question';
if ($pos = $this->_processId($this->_post->getRaw('question_id')))
{
$project->goto($pos);
$action = 'review'; // change where we're forwarding
}
$answer = $this->_validateAnswer();
$project->addAnswer($answer);
if ($this->_ajax)
{
// output ajax response
return;
}
/**
* If there were any issues with adding the answer, _validateAnswer
* will have already taken care of the error messages, etc. so
* it is safe to simply forward the user to the question action now
*/
$this->_forward('project', $action);
return;
}