Im trying to get Cakephp 3 send a json reply to my javascript function when i call it but i dont know the correct way to do it..
JS function:
function add(){
//serialize form data
var formData = $('#newquestion').serialize();
//get form action
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: formData,
success: function(status){
console.log('content='+status);
},
error: function(xhr,textStatus,error){
alert(error);
} });
}
CakePHP 3 action:
public function addajax(){
if ($this->request->is('ajax')) {
$status['msg']="this is a message from cake controller";
$this->response->body(json_encode($status));
return $this->response;
}
}
Question: The above cakephp action works and sends the correct output but is it correct; Am i not suppose to use an ajax view or ajax layout?
When i use serialize as below it doesnt work, comes up as "undefined" in the javascript function function. What am i doing wrong? and whats the correct way to do it?
Is the below example not correct also?
public function addajax(){
if ($this->request->is('ajax')) {
//$this->viewBuilder()->layout('ajax');
//$this->autoRender = false; // Set Render False
$status['msg']="this is a message from cake controller";
$this->set(compact('status'));
$this->set('_serialize', ['status']);
//$this->response->body(json_encode($status));
//return $this->response;
}
}
PS: i have enabled JSON and XML routing and views.