Ajax bad request 400

I am using the following code to make an ajax request to a controller:




            var data = JSON.stringify({

                'user_id': '<?=$user->id?>',

                'package_id': '<?=$bundle->package_id?>',

                'YII_CSRF_TOKEN': '<?=Yii::app()->request->csrfToken?>'

            });


            $.ajax({

                url: "<?=$this->createUrl('bundle/ajaxRemove')?>",

                data: data,

                type: "POST",

                contentType: "application/json",

                dataType: "json",

                error: function (xhRequest, ErrorText, thrownError) {

                    alert("Failed to process user correctly, please try again");

                    console.log('xhRequest: ' + JSON.stringify(xhRequest) + "\n");

                    console.log('ErrorText: ' + ErrorText + "\n");

                    console.log('thrownError: ' + thrownError + "\n");

                }


            }).done(function (msg) {

                console.log(msg);

            });



In the controller, I have this:




    public function actionAjaxRemove()

    {

        if (Yii::app()->request->isPostRequest) {

            $userId = $_POST['user_id'];

            $packageId = $_POST['package_id'];


            $isDeleted = UserPackageLink::model()->deleteAllByAttributes([

                    'user_id' => $userId,

                    'package_id' => $packageId

                ]);


            if ($isDeleted) {

                $result = [

                    'status' => 'true',

                    'message' => 'User was successfully removed from this package.'

                ];

            } else {

                $result = [

                    'status' => 'false',

                    'message' => 'A problem occurred: User FAILED to be removed!'

                ];

            }


            echo CJSON::encode($result);

        }else {

            echo "No post data found";

        }

    }



The problem is, whenever I submit the ajax code, Yii consistently returns a 400 Bad Request error.

I’ve tried sending the data as regular post data instead of JSON, but still getting the same error. Tearing my hair out here!

Any idea what I am doing wrong?

doc

try:




var data = JSON.stringify({

    // ...

    '_csrf': yii.getCsrfToken()

});