Welcome Guest, Not a member yet? Register   Sign In
CI3 file upload via ajax with csrf
#4

(This post was last modified: 06-04-2020, 12:24 AM by thejmf.)

1-inspect(f12) your html to make sure that you can see the csrf_token usually is next tag afther <form> open tag
example <input type="hidden" name="csrf_token" value="4d924356536aca777f04c56ade9a8ce7"> if the token is not there any POST request will be 403 forbidden-->hint if you use the form helper to open your forms it will be there 
on the server side
2-
PHP Code:
function fileUpload(){
#do your upload methods
//respond back as json
if(your_condition){ // if upload succesful

$response=[
'crsf_token' => $this->security->get_crsf_hash(),
'status'=> 'success'  
];
}else{ 
//if upload unsuccessful
$response=[
'crsf_token' => $this->security->get_crsf_hash(),
'status'=> 'unsuccess'  
];
}
exit (
json encode($response));



success or not success you always must reset crsf token 
your javascript
3-var formData = new FormData(this);
            var file_data = $('#document').prop('files')[0];
          formData.append('file', file_data);
** this is going to work fine. however when your ajax respond back it must bring a new csrf_token to replace the old one.
example;
Code:
$.ajax({

              url:'YOUR URL',
              type:"POST",
              data:formData ,
              cache: false,
              contentType: false,
              processData: false,
              success: function (responseJson) {
                  $('input[name=csrf_token]').val( responseJson.csrf_token);  <----this is the key refresh the token
               }
   

        }); 


like dave mentioned you can only use the a token one time
Reply


Messages In This Thread
CI3 file upload via ajax with csrf - by Goddard - 06-03-2020, 07:43 AM
RE: CI3 file upload via ajax with csrf - by thejmf - 06-04-2020, 12:19 AM



Theme © iAndrew 2016 - Forum software by © MyBB