CodeIgniter Forums
csrf regenrate in ajax post - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forum-30.html)
+--- Thread: csrf regenrate in ajax post (/thread-76478.html)



csrf regenrate in ajax post - cilux - 05-15-2020

I have this code for post data using ajax:

Code:
        $("selector").select2({
            minimumInputLength: 3,
            theme: 'bootstrap4',
            width: 'auto',
            ajax: {
                url: "<?= route_to('autocomplete'); ?>",
                type: "post",
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        searchTerm: params.term,
                        csrf_token: csrf_token // token get from js var
                    };
                },
                processResults: function(response) {
                    return {
                        results: response
                    };
                },
                cache: true
            }
        });

if I enable token regenerate, my code work only for first post data.

I not found best practice for fix csrf token regenerate in multiple ajax post. any one can help!?


RE: csrf regenrate in ajax post - seunex - 05-15-2020

Why not the filter to tell card to ignore the actual controller and do some checking in the controller by checking if the actual post I ajax request


RE: csrf regenrate in ajax post - cilux - 05-16-2020

Sorry but whats your mean ?!


RE: csrf regenrate in ajax post - InsiteFX - 05-16-2020

Read this.

Codeigniter CSRF valid for only one time ajax request

For CI 3 but should work in CI 4.


RE: csrf regenrate in ajax post - cilux - 05-16-2020

(05-16-2020, 03:14 AM)InsiteFX Wrote: Read this.

Codeigniter CSRF valid for only one time ajax request

For CI 3 but should work in CI 4.

I read it before, this is not clear way for add token in each ajax json response controller. i think codeigniter need to laravel solution like this


RE: csrf regenrate in ajax post - InsiteFX - 05-16-2020

Maybe something like this, not tested.

Code:
$(function($) {

    // this script needs to be loaded on every page where an ajax POST may happen

    $.ajaxSetup({
        data: {
            // you would need to load the Security Lib in the Controller.
            '<?php echo $security->getCSRFTokenName(); ?>' :
            '<?php echo $security>getCSRFHhash();?>'
        }
    });

    // now write your ajax script

});

Not sure if the view would see the security lib from the controller.

I'll play around with this later on.