CodeIgniter Forums
CSRF + ajax/jquery problem - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forum-5.html)
+--- Forum: Best Practices (https://forum.codeigniter.com/forum-12.html)
+--- Thread: CSRF + ajax/jquery problem (/thread-68880.html)



CSRF + ajax/jquery problem - fedde - 09-08-2017

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.


RE: CSRF + ajax/jquery problem - dave friend - 09-08-2017

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...
},



RE: CSRF + ajax/jquery problem - fedde - 09-08-2017

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!