Reputation: 477
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.
Upvotes: 0
Views: 10417
Reputation: 151
$this->response->withType('application/json')->withStringBody(json_encode($format));
with $format
is your array.
Upvotes: 4
Reputation: 1413
Your are will send php array via json, then you are encode an array in php and parse the response in js function
Try this in your CakePhp 3 action:
public function addajax(){
$this -> autoRender = false;
if ($this -> request -> is('ajax')) {
$status['msg']= "this is a message from cake controller";
return json_encode($status);
}
}
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){
var json = JSON.parse(status);
console.log('content='+json.msg); // .msg is name of your index $status['msg']
},
error: function(xhr,textStatus,error){
alert(error);
}
});
}
Upvotes: -1