Codeigniter CSRF valid for only one time ajax request

前端 未结 9 877
鱼传尺愫
鱼传尺愫 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:46

    Each time you make a request, the csrf_token is being updated by CI. That's why the CSRF only work once. So everytime we make a request we need to update the csrf_token too. I solve this problem by doing this.

    Conroller: get the updated csrf using this code.

    public function update_csrf()
    {
      $data['csrf_hash'] = $this->security->get_csrf_hash();
      echo json_encode($data);
    }
    

    AJAX: replace the old value of your csrf name="csrf_token_name"

    var jqXHR = $.ajax({
                url: $(this).attr('action'),
                type: 'POST',
                data: $(this).serialize(),
                dataType: 'json',
            })
            jqXHR.done(function(response) {
                $('input[name=csrf_token_name]').val(response.csrf_hash); //update the csrf to the form 
            })
            jqXHR.fail(function(jqXHR, textStatus, errorThrown) {
                console.log(jqXHR);
                console.log(textStatus);
                console.log(errorThrown);
            });
    

    Important!: use dataType: 'json'

    So now each time you have a successful request, the csrf_token is updated too and you are now free from 403 (Forbidden) error.

提交回复
热议问题