I have the following jQuery code. The purpose of the code is to send the json data in the data setting to the CakePHP addSourceDocuments() function in the DocumentsController controller (hence, the '/documents/addsourcedocuments' in the 'url' setting).
jQuery.ajax({
type: 'POST',
url: '/documents/addsourcedocuments',
accepts: 'application/json',
data: {
sourceFileName: file.name,
sourceFileId: file.id
},
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error!");
}
});
The CakePHP Documents controller has the following code. I used the instructions from the CakePHP Cookbook 2.x "JSON and XML views" page (http://book.cakephp.org/2.0/en/views/json-and-xml-views.html) in an attempt to return json data from a CakePHP controller without a view.
class DocumentsController extends AppController {
public $components = array('RequestHandler');
public function index() {
$this->layout = 'index';
}
public function addSourceDocuments() {
$this->autoRender = false;
if ($this->RequestHandler->isAjax()) {
Configure::write('debug', 0);
}
if (!empty($this->data)) {
$this->log($this->data, 'debug');
$this->set('response', 'here is the newest content');
$this->set('_serialize', array('response'));
}
}
}
I also have the following in my routes.php file (as instructed by the "JSON and XML views" page mentioned above).
Router::parseExtensions('json');
While the CakePHP controller successfully receives the data from the jQuery ajax call (the $this->log($this->data, 'debug'); is writing the received data to the log and it is the data I expect to receive), the CakePHP controller is returning no data (the jqXHR.responseText value in the error setting of the jQuery.ajax call is an empty string). The only other information provided is that the errorThrown.message setting has a value of "Unexpected end of input" and the textStatus setting has a value of "parsererror."
I expect that the success setting of the jQuery.ajax call should contain 'here is the newest content' in the data variable because the addSourceDocuments() function is setting that value with the _serialize key word. Obviously, that isn't happening.
So, what did I do wrong?
Thanks!