Regenerate CRSF token codeigniter on submit Ajax

后端 未结 5 577
遥遥无期
遥遥无期 2021-01-07 04:46

Hi I am looking for the process of regeneration of csrf token in codeigniter when ever a form is submitted using ajax. I want the token to be regenerated without page refres

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-07 05:14

    if it's not on session then you controller will be like this

    public function save_date() // or whatever function you like
    {
     $regen_token = $this->security->get_csrf_hash();
     $data = array(
          "data" => $this->input->post('datas'),
     );
     $insert = $this->w_m->save($data);
     echo json_encode(array("regen_token" => $regen_token));
    }
    

    in your ajax will be look like this:

    $.ajax({
     url: "your url",
     type: "POST",
     data: { your data },
     dataType: "JSON",
     success: function(data)
     {
      $("name or id of your csrf").val(JSON.stringify(data.regen_token)).trigger("change"); // this will be the function that every post you'll request and it automatically change the value of your csrf without refreshing the page.
     },
     error: function(errorThrown)
     {
       console.log(errorThrown);
     }
    });
    

提交回复
热议问题