1

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');
    }
Malcom HAMELIN
  • 305
  • 1
  • 3
  • 11
  • *"but I keep getting ... Internal server error ...'"*, check your log (\runtime\logs). – Definitely not Rafal Jun 24 '21 at 11:17
  • @DefinitelynotRafal "Unable to verify your data submission", that's what the logs says – Malcom HAMELIN Jun 25 '21 at 05:34
  • Does this answer your question? [Why get Unable to verify your data submission error in Yii2?](https://stackoverflow.com/questions/26459419/why-get-unable-to-verify-your-data-submission-error-in-yii2) or [Getting bad request (#400) on Ajax calls using Yii 2](https://stackoverflow.com/questions/27126050/getting-bad-request-400-on-ajax-calls-using-yii-2) – Definitely not Rafal Jun 25 '21 at 08:47
  • You could see what's inside the sent body request, to see if the request is valid, also you can give more details about yii app error log, to see step by step what's happening – Diego Tejada Jun 25 '21 at 22:37

0 Answers0