Hii are someone know the best ways to regenerate csrf token on ajax form submit

My apologies for just seeing this right now! I know this topic is a few months old, and you've probably already figured it out ... but I can't help myself. I use Codeigniter's CSRF token and I use AJAX a lot. (Note: I use Codeigniter 3).

So, here's what I do:

In my views/header.php template (that appears at the top of every page of the site within the <head>) I have:

    <!-- CSRF Hash -->
    <script>var dw_csrf_hash = '<?= $this->security->get_csrf_hash() ?>';</script>

Note that I have dw_csrf_hash hard coded but it doesn't have to be. You could do something such as $this->config->item('csrf_token_name') or config_item('csrf_token_name').

Then, I have a controller class that looks like this:

class Ajax extends CI_Controller
{
    public function csrf()
    {
        $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode(array(
            'csrf_hash' => $this->security->get_csrf_hash(),
        )));
    }

    function __construct()
    {
        parent::__construct();

        // We want to make sure we're making the JSON call every time
        $this->output->set_header("X-Robots-Tag: noindex");
        $this->output->set_header('Cache-Control: no-store, no-cache');
    }
}

So you can see that I can call the URI ajax/csrf in order to retrieve JSON that includes the latest csrf token value.

Now that I have a global Javascript variable that stores the CSRF token, here is what my AJAX calls look like (note, I use jQuery, but you get the idea):

function get_csrf()
{
    // Retrieve the latest value of the CSRF hash and update the global JS variable
    $.get('/ajax/csrf', function(data) {
        dw_csrf_hash = data.csrf_hash;
    });
}

// Every time an AJAX call is made, call the get_csrf() function
$(document).ajaxComplete(function(event, data, settings) {
    get_csrf();
}); 

Then, for each AJAX POST call that I make, I simply need to pass in the latest value of the CSRF token as a POST parameter.

I've actually taken it a bit further so that each of my AJAX requests return back the latest value of the CSRF token in their JSON payload. So I don't have a need to make a separate call to ajax/csrf anymore (except in rare edge cases).

Good luck, and hopefully this can help others! Again, sorry for seeing this 4 months too late.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.