Reputation: 822
I have an ajax call from my javascript file that is attempting to post data to a specific function in my controller. When I view the data in the success function of my call, I get the html of a totally unrelated view as the returned data, and I am unsure why.
My AJAX call:
function processResults(task_id){
var finalResults = localStorage.getItem('results');
console.log(finalResults);
$.ajax({
type: 'POST',
url: 'task/getResults',
data: {'answers': finalResults},
success: function(data){
console.log(data);
}
});
}
My Controller function:
public function getResults(){
$this->load->model('testResults');
$finalResults = $this->input->post('answers');
$finalResults = json_decode($finalResults, true);
if ($taskTestId != '') {
$this->testAnswers->insertTaskData($finalResults);
}
}
Is the url in the ajax call incorrect? I'm not really sure why it is outputting the html of a completely unrelated view. Any help would be appreciated!
Upvotes: 0
Views: 659
Reputation: 13
Tpojka answer will work.
But there is a more elegant way to return a JSON objet with CI
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
http://www.codeigniter.com/userguide3/libraries/output.html#CI_Output::set_content_type
Upvotes: 0
Reputation: 7111
Last line controller/method
passed in AJAX should be echo of something. At the end you would have something like:
if ($expression) {
echo json_encode($something);
} else {
echo json_encode($something_else);
}
Upvotes: 1