• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
csrf token is valid just in first submit using ajax

#6
(12-24-2015, 01:17 PM)iamthestreets Wrote:
(04-08-2015, 12:15 PM)mwhitney Wrote: Another method would be to return the new csrf hash in the response to your AJAX post, then update the value of the csrf token field in your table in the $.ajax success callback. Then you could just change your data to retrieve the value from the field instead of using "<?=$this->security->get_csrf_hash();?>" in the script.

You could also retrieve the URL from the form so you don't have to repeat that information in the script.

I know this is an old thread but could you give an example of how to do this?

My JavaScript/jQuery is a bit rusty, so any example code below might need some work before it functions properly.

One of the easiest ways to manage this would be to add one or two hidden inputs to the form to hold the token/hash values. The inputs would be filled in the usual manner when the form is loaded (either by passing the data to the view or by calling the security methods in the view).

When posting the data in the JavaScript, instead of calling the security methods, you would get the values of the hidden inputs:

Code:
data : {
    $('#csrfTokenName').val() : $('#csrfHash').val(),
    "username": "username01"
}

In the controller method which responds to the AJAX request, you would call $this->security->get_csrf_hash() and $this->security->get_csrf_token_name() and place the values in the result. For example, you might return an object with the requested data, the hash, and the token name:

Code:
class Ajaxcontroller
{
    public function ajaxmethod()
    {
        // get your data, then prep the returned value:
         $result = '{
             "resultData": "some data here",
            "csrfTokenName": "'.$this->security->get_csrf_token_name().'",
            "csrfHash": "'.$this->security->get_csrf_hash().'"
        }';
        // ... send it back to the browser

    }
}

Then your JavaScript would just process the result and update the inputs with the values from the csrfTokenName and csrfHash values in the result.

Code:
.success:function(result){
    $('#csrfTokenName').val(result.csrfTokenName);
    $('#csrfHash').val(resuit.csrfHash);
}

After that, the inputs will contain the new values instead of the values received when the page initially loaded, and the next AJAX request should work properly.
Reply


Messages In This Thread
RE: csrf token is valid just in first submit using ajax - by mwhitney - 12-29-2015, 09:59 AM

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.