在Codeigniter CSRF中的Ajax调用错误函数中禁止 [英] forbidden in ajax call error function in codeigniter csrf

查看:202
本文介绍了在Codeigniter CSRF中的Ajax调用错误函数中禁止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用codeigniter,我想通过ajax将一些数据插入数据库,但是我的ajax调用有问题;
我已经搜寻了两个小时,但无法解决问题。
我的问题是,当我单击提交按钮时,它说被禁止。

另外,我的csrf保护设置为TRUE!请帮助,谢谢

I'm just getting started with codeigniter I want to insert some data into database via ajax but I have a problem with my ajax call; I've been searching for two hours but I could not solve the problem. My problem is when I click on submit button it says forbidden.
Also my csrf protection is set to TRUE! Please help, thanks

JS

$(document).ready(function() {

$(".addbtn").click(function (e) {
        e.preventDefault();
        if($("#mname").val()==='' || 
           $('#sname').val() === '' || 
           $('#genre').val()==='' || 
           $('#album').val()==='' ||
           $('#publishyear').val() ==='' ||
           $('#artist').val()==='')
        {
            alert("Please fill all the fields!");
            return false;
        }

        $("#FormSubmit").hide(); 
        $("#LoadingImage").show(); 

        var baseurl = "<?php echo base_url(); ?>";
        var data = {
                'mname': $("#mname").val(),
                'sname': $('#sname').val(),
                'genre': $('#genre').val(),
                'album': $('#album').val(),
                'publishyear': $('#publishyear').val(),
                'artist': $('#artist').val(),
                '<?php echo $this->security->get_csrf_token_name(); ?>':
                '<?php echo $this->security->get_csrf_hash(); ?>'
                };

        $.ajax({
        type: "POST", 
        url:  baseurl+"index.php/admin_page/send_ajax", 
        data: data, 
        success:function(){
            alert("success");

        },
        error:function (xhr, ajaxOptions, thrownError){
            $("#FormSubmit").show(); 
            $("#LoadingImage").hide(); 
            alert(thrownError);
        }
        });
  });});

配置文件

$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();

控制器

public function send_ajax(){


    $data = array(
                'name_of_music'=>$this->input->post("mname", TRUE),
                'artist'=>$this->input->post("artist", TRUE),
                'name_of_singer'=>$this->input->post("sname", TRUE),
                'genre'=>$this->input->post("genre", TRUE),
                'album'=>$this->input->post("album", TRUE),
                'publishyear'=>$this->input->post("publishyear", TRUE)
            );
    $json_data['lyrics_info_data'] = json_decode($data);
    $this->user_model->insert_json_in_db($json_data);
  }

模型

public function insert_json_in_db($json_data){
    $this->db->insert('lyrics', $json_data);
  }


推荐答案

您可以确认什么是使用此行 $ json_data ['lyrics_info_data'] = json_decode($ data); 吗?我认为这行是错误的。

Can you confirm what is the use of this line $json_data['lyrics_info_data'] = json_decode($data); ? I think error is with this line.

您可以使用 $ json_data ['lyrics_info_data'] = $ data; 代替 $ json_data ['lyrics_info_data'] = json_decode($ data);

还需要更新模型函数。

public function insert_json_in_db($json_data){
    $this->db->insert('lyrics', $json_data['lyrics_info_data']);
}

脚本更新

Codeigniter将在每次请求时重新生成其crcf令牌,并且此信息将存储在cookie中。因此,您需要从cookie中获取令牌值,并将其与要传递的ajax数据一起发送。我对Folliwing JavaScript所做的事情是,使用通用函数将crcf值与所有ajax请求一起附加。

Codeigniter will regenerate its crcf token on each request and this info will be stored in cookie. So token value you need to take from cookie and send along with ajax data you are passing. What I am doing with folliwing javascript is that, using a common function to attach crcf value along with all the ajax request.

在jquery中,有一个选项可以将自定义数据与ajax请求一起添加。
请参见jquery文档 http://api.jquery.com/jquery.ajaxprefilter/有关更多详细信息

In jquery there is an option to add custom data along with ajax request. See jquery documentation http://api.jquery.com/jquery.ajaxprefilter/ for more details

<script>
   $(document).ready(function(){ 

function getCookie(c_name) { // A javascript function to get the cookie value 
    if(document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if(c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if(c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}

$.ajaxPrefilter(function(options, originalOptions, jqXHR){ // This function will attach "csrf_test_name" with all the request you are sending. 
    if (options.type.toLowerCase() === "post") { // Required only if its a post method 
        var csrf_token = getCookie("csrf_test_name");
        // initialize `data` to empty string if it does not exist
        options.data = options.data || "";

        // add leading ampersand if `data` is non-empty
        options.data += options.data?"&":"";

        // add _token entry
        options.data += "csrf_test_name=" + csrf_token;
    }
});
 });
   </script>

您可以删除'<?php echo $ this->安全性-> get_csrf_token_name(); ?>’:‘<?php echo $ this-> security-> get_csrf_hash(); <>’来自 var data

重要说明:如果在config.php中更改 $ config ['csrf_token_name'] ='csrf_test_name'; 那么您还需要更新此脚本。

Important note: if you change $config['csrf_token_name'] = 'csrf_test_name'; in config.php then you need to update this script as well.

请在更新代码后尝试,让我知道问题是否仍然存在。

Please try after updating your code and let me know if issues still exists.

这篇关于在Codeigniter CSRF中的Ajax调用错误函数中禁止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆