Codeigniter CSRF valid for only one time ajax request

前端 未结 9 837
鱼传尺愫
鱼传尺愫 2020-12-03 11:46

I want to upload image on the server on change event of jQuery but using codeigniter csrf I am able to upload image only one time. How can I upload images using ajax for mul

9条回答
  •  有刺的猬
    2020-12-03 11:57

    $config['csrf_regenerate'] = TRUE;

    keep auto generate to true it will be more safer. In similar case when csrf is expired in first request. What i have implemented

    $(document).ajaxComplete(function (event, xhr, settings) {
     let response = xhr.responseText,
     let obj = JSON.parse(response),
     let csrfData = obj.csrf;
     document.querySelector('input[name="' + csrfData.name + '"]').value = csrfData.hash; 
    }); //Also here you can update any other non input element    
    

    In every ajax response we are passing csrf data in which latest csrf data will be replaced with current one

    Sample response from request

    { 
    csrf : {
      name : 'csrf_name',
      hash : 'qw76sd7s6f78sdfs8dfs9df8cx9'
     }
    }
    

    I update csrf token in every ajax request. Also don't choose this method if you are working with multi tab environment

提交回复
热议问题