I have two dropdown list which is question and answer. At first the answer dropdown list is empty, after the user choose a question, then it will pass the question_id to controller to run a function to get the answer. After the controller get the result, it will pass to the correspond view. Now how can I pass the result to the index view?
the index view:
$("#id_question").change(function() {
var data = $("#id_question").val();
var dataToSend = {question: data}
var href= '<?php echo $this->baseUrl('admin/comment/checkanswer'); ?>';
$.ajax({ type: "POST",
url: href,
data: dataToSend,
success: function(response){
//do what u wana do
}
});
});`
the controller:
public function checkanswerAction()
{
$this->_helper->layout->disableLayout();
$question_id = $this->getRequest()->getParam('question');
$answer_model = new Admin_Model_DbTable_Answer();
$answer = $answer_model->getAnswersByQuestionId($question_id);
$this->view->answer = $answer;
}
the checkanswer.phtml:
foreach ($this->answer as $key => $value)
{
echo '<option value="'.trim($value['id_answer']).'">'. trim($value['answer_text']) .'</option>';
}
The content that should be displayed in checkanswer.phtml
will be affected to your javascript var response
. So if you want to display this in your page, you have to make something like this :
success: function(response){
//do what u wana do
$('#yourSelectID').html(response);
}
with ajax you should always use these two things
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true); // this you have not used.
And in ajax resonse
success: function(response){
$('#id_answer').html(response);
}
There's a bug in your action: $this->getRequest()->getParam('question');
. It gets a parameter passed using GET but you are passing using POST. So you should use $this->getRequest()->getPost('question');
. If you add HTML like others suggested it should work. If it doesn't, use firebug or chrome developer tools to see what was returned by server and whether wrong output is returned by the server or there's a bug in parsing it with JS.
But this approach won't work out all the time (outputting formatted HTML) because it's simply inflexible. For instance, you want to use this ajax endpoint in other application (or different platform even, such as Android), or you want to modify the data in client side before printing, etc.
The solution here is to use context switching. Won't go into a lot of details now because I believe the link contains enough information, let me know if you have any questions.