I want to send data in json format in cakePHP.
Good evening, this is Bono.
It seems there was an earthquake of intensity 4 in Miyagi just now. That was pretty long.
I was making a map service and had a situation like that, but it seemed so simple that I didn't understand it surprisingly, so I'm leaving it here.
XXXController.php
return new CakeResponse(array('body' => json_encode(array(
'content'=> $data['Question']['content'],
'place_lat'=> $data['Question']['place_lat'],
'place_lng'=> $data['Question']['place_lng']
))));
Add this sentence to the end of the controller.
Incidentally, Question here is the model name, and content, place_lat, and place_lng are the column names.
XXX.ctp
$("#questionBtn").bind("click",
function (e){
$.ajax({
data: $("#questionBtn").closest("form").serialize(),
dataType: "json",
success: function (data){
console.log("私は"+data.place_lat +", " +data.content);
plusMarker(data);
},
type: "post",
url: "getAjax"
});
return false;
}
);
This time, a form is used, and when the questionBtn is pressed, data is sent to the getAjax action of XXXController using Ajax.
Then the above XXXController sends a response in json format, which is passed to the plusMarker() function.
Data is in json format. Checked console.log to be sure.