I'm currently to send some Ajax request in my Yii2 application, but I keep getting 'Bad request 500 (Internal server error)' errors in my console.
I'm trying to do something simple and I'm new to AJAX, so just passing data from a text input when I click on a button to my controller and see how it's formatted (through var_dump).
I tried disabling crsf token in beforeAction and it works, but I don't want to disable it.
Here is my Ajax request :
<script>
// Bind to the submit event of our form
$(document).on('click', '#sendButton', function() {
var newMessage = $('#newMessage').val();
var myUrl = "<?php echo Url::to(['chat/send']); ?>"
$.ajax({
url: myUrl,
type: "POST",
data: {newMessage: newMessage, _csrf: '<?=\Yii::$app->request->csrfToken?>'},
success: function(response) {
console.log("Hooray");
}
});
});
</script>
And here is my Yii2 action :
public function actionSend() {
$data = Yii::$app->request->post();
var_dump($data);
return $this->render('dump');
}