How to create a javascript function to send a AJAX request to your cakePHP controller action;
function testajaxadd(question_id,answerindex){
var mydata=new Object();
mydata.question_id=question_id;
mydata.answerindex=answerindex;
jQuery.ajax({
type:'POST',
async: true,
cache: false,
data: mydata,
url: 'http://localhost/myquiz/questions-answers/ajaxadd',
success: function(response) {
//success
console.log(response);
},
error: function(response) {
console.log(response);
}
});
}
Cakephp controller action;
public function ajaxadd(){
$questionsAnswer = $this->QuestionsAnswers->newEntity();
if ($this->request->is('ajax')) {
$questionsAnswer = $this->QuestionsAnswers->patchEntity($questionsAnswer, $this->request->data);
// Added this line which makes the record belong to the logged in user
$questionsAnswer->user_id = $this->Auth->user('id');
if ($this->QuestionsAnswers->save($questionsAnswer)) {
$status['msg']="Saved Record";
} else {
$status['msg']="Error Saving Record";
}
//return the message to js function
$this->response->body(json_encode($status));
return $this->response;
}
}