Welcome Guest, Not a member yet? Register   Sign In
CSRF + ajax/jquery problem
#1

Hi all

I got a little question about CSRF and ajax when enabling the $config['csrf_regenerate'] = TRUE; in the CI config.  I have searched alot, tested diffrent solutions on stackexchange, found some here but nothing that does not give me a 403 after the first submission of the ajax. 

I use form helper to create form, the csrf hidden field is inserted automatic. 

My ajax code is 
Code:
$('#testform').submit(function(e){
       e.preventDefault();
       $.ajax({
           url: url_base+'csrftest/submit',
           type:'post',
           data:$('#testform').serialize(),
           success:function(results){ //alert(results);
                // Some code for refreshing stuff...
           },
           error: function (xhr, ajaxOptions, thrownError) {
             alert(xhr.status);
             alert(thrownError);
           }
       });
   });

I have read about the jquery $.ajaxSetup but with no luck on getting it working when you use regeneration.

What is best practices and what solutions do you guys use when the page is not refreshed?  Of course, disable the csrf regeneration all works as expected. 

Thanks in advance.
Reply
#2

(This post was last modified: 09-09-2017, 09:41 AM by dave friend.)

You will need to return the new CSRF hash value to your ajax success method and use the value to update the hidden CSRF field.

In the controller you can use the security class to get the CSRF token name and hash like this

PHP Code:
$token $this->security->get_csrf_token_name();
$hash $this->security->get_csrf_hash(); 

Then, assuming you will return json data, echo a json encoded array containing this info... and anything else needed to update the page.

PHP Code:
echo json_encode(array('token' => $token'hash' => $hash'other' => $something'more_stuff' => $more); 

Then, back at the .ajax success function, some javascript along these lines to update the CSRF field

Code:
success: function (results) {
   //find the CSRF field and update with new hash value
   $("input[name=" + results.token + "]").val(results.hash);

  // code for refreshing other stuff...
},
Reply
#3

Ah, then i was close one time, was playing abit with the success and return a new hash but could not quite get it to work. will try your method, it looks good.

Thanks!
Reply




Theme © iAndrew 2016 - Forum software by © MyBB