I'm trying to send a simple AJAX request from my view, and I'm using cakePHP's JSON view to do so, but I'm unable to get _serialize to prevent the controller from seeking a ctp file--I consistently get a "Status 500: view file ... is missing" error. I've read the docs and several similar questions on stackoverflow, and I can't see what I'm missing.
I've added the requesthandler to my initialize function in AppController:
public function initialize() {
$this->loadComponent('RequestHandler');
}
enabled extensions:
Router::parseExtensions('json');
require CAKE . 'Config' . DS . 'routes.php';
I've added the component to my controller:
class StudentsController extends AppController {
public $name = 'Students';
public $components = array('RequestHandler');
The only thing that seems to change it is when I add the following code to AppController's beforeFilter method--just renders the word "null":
$this->RequestHandler->renderAs($this, 'json');
$this->response->type('application/json');
$this->set('_serialize', true);
This is my controller method:
public function set_rating() {
$this->autoLayout = false;
$this->autoRender = false;
$this->response->type('application/json');
$studentID = (int) $this->request->data['studentID'];
$rating = (int) $this->request->data['rating'];
$this->Student->id = $studentID;
if($this->Student->saveField('rating', $rating)) {
$this->set('success', 1);
}
else{
$this->set('success', 0);
}
$this->set("_serialize", array("success"));
}
and the Ajax request:
$.ajax({
url: '<?php echo $this->webroot . $this->params["controller"]; ?>/set_rating.json',
type: "POST",
dataType: "json",
data: {studentID: text, rating: value},
success: function(response) {
if(response['success'] == 1){
manageFlashMessage('alert-success', 'Rating saved.');
}
else {
manageFlashMessage('alert-danger', 'Sorry, something went wrong');
}
},
error: function (xhr, status, error) {
console.log(xhr.status);
console.log(xhr.responseText);
console.log(status);
}
});
I can't see what I'm missing! Any ideas?