Multiple Datatables on same page and csrf token

Multiple Datatables on same page and csrf token

johndoojohndoo Posts: 18Questions: 5Answers: 1

My current csrf token handling with one single datatable on the page works fine.

But now I try to use jquery.load('another local url') to insert some html and another datatable in a div of the same page and of course it breaks the csrf token handling.

1) main page is loaded and csrf_token_value1 is stored in a javascript variable A

2) the main page calls jquery.load('another url') that has also a variable B that will contain csrf_token_value2

3) when I try to search in the main page datatable I obtain a 403 error because A contains now an outdated csrf_token

  • when loading the subpage I cannot do A=B because A is "undefined" in the scope of the jquery loaded subpage.
  • on the PHP server side, there is only one shared csrf_token

Any suggestion ? Can I store the csrf token in localstorage instead of a variable to solve the problem ?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,173Questions: 26Answers: 4,923
    edited December 2020

    Just to be clear you are using the jQuery load() method to fetch your data for the second Datatable?

    How are you populating the CSRF token for the first Datatable? If using ajax.data is it being used as a function?

    Maybe you can post your code or better a link to your page or a test case so we can see what you have. This will give us the information needed to help you with how to access your CSRF taken variable.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Checkout this this information:
    https://datatables.net/manual/security#Cross-Site-Request-Forgery

    Kevin

  • johndoojohndoo Posts: 18Questions: 5Answers: 1
    edited December 2020

    My page is in a private extranet, I cannot put the url here. I will try to create a public page with the exact same code and then post it.
    To answer your questions:
    * jquery load() is used to get the whole html/js code of another page that will be inserted in a div of the main page, and this loaded code contains js to initialize a second datatable (the first one is in the main page)
    * I use ajax.data as a function and the CSRF token is populated twice (one time per datatable)
    * I use serverside data on both datatables

  • johndoojohndoo Posts: 18Questions: 5Answers: 1
    Answer ✓

    I have solved my issue. I have refactored a lot of code and then I modified CSRF handling , I removed the javascript variable and used a hidden input field with special class to be able to share the last CSRF token across all forms.

    Happy new year to everyone.

  • allanallan Posts: 63,214Questions: 1Answers: 10,415 Site admin

    Thanks for posting back. Good to hear you've got it working!

    Happy New Year!

    Allan

This discussion has been closed.