How to enable CSFR with ajax?

I am sending ajax post request and it seems that _csrf parameter is completly ignored.




         $form = ActiveForm::begin(['id' => 'csrf-forma',]);

            echo $form->field($csrfModel,'returnUrl')->hiddenInput();

         ActiveForm::end();     

        $this->registerJs("$(document).ready( function(){ 

                    var returnUrl = window.location.href;

                    $('.link').click(function(e)

                    {

                        e.preventDefault();                        

                        var url = $(this).attr('href');

                        $('#dummyform-returnurl').val(returnUrl);

                        var forma = $('#csrf-forma').serialize();

                        $.post(url, forma);

                    });

                } );");



On the server side I can make an istance of DummyForm and it doesn’t matter if _csrf is correct or not if DummyForm is sent through ajax post request.

How are you testing that it is ignored?

I am using an AJAX based form submit myself and actually just now was testing thr CSRF checking. It seemed to me that it would still accept it if I changed the _csrf token value in the form but if I changed the meta tag for csrf-token it would get an error.

So not sure if that is correct behavior or not - have you tried this?

I changed _csrf token to some random value and it had no effect when submited through ajax. When I change _csrf token and submit it "regular way", it raises exception as I expected.

Try changing the meta tag token and see what happens.

I did that and still no effect. It must be that I am doing something wrong.

P.S.

Only if I change both _csrf and meta tag token I get an exception. I dont get it.

This is what I get back when I change the _csrf_token in the meta tags:


Bad Request (#400): Unable to verify your data submission.

But as I said, just changing the form one itself has no effect.

Maybe you could post more of your code such as from your view?