简体   繁体   English

在Ajax中在Codeigniter中启用csrf时收到403禁止错误

[英]getting 403 forbidden error when using ajax with csrf enabled in codeigniter

I am using codeigniter with csrf enabled. 我使用启用了csrf的codeigniter。 i am making some ajax post requests but somehow i am getting 403 post forbidden error. 我正在发出一些ajax发布请求,但不知何故我收到403发布禁止错误。 my folder structure is like this i have included this js in which ajax code is written outside of application folder. 我的文件夹结构是这样的,我已经包含了这个js,其中ajax代码是在应用程序文件夹之外编写的。 the code i am using for ajax request is 我用于ajax请求的代码是

var data = {
    name: $('.name').val(),
    crm_csrf_token: $('input[name="crm_csrf_token"]').val()
} 
var url = 'http://demo/signup/signup';
$.ajax({
    url: url,
    dataType: 'json',
    type: 'post',
    contentType: 'application/json',
    data: data,
    success: function( data, textStatus, jQxhr ){
        console.log(data);
        console.log(textStatus);
        console.log(jQxhr);
    },
    error: function( jqXhr, textStatus, errorThrown ){
        console.log(jqXhr);
        console.log(textStatus);
        console.log(errorThrown);
    }
});

so where am i going wrong. 所以我要去哪里错了。 before making this ajax call i am validating form using javascript too. 在进行此ajax调用之前,我也正在使用javascript验证表单。 site_url() and base_url is not accessible outside application forlder too. 也无法在应用程序外部访问site_url()和base_url。

Try this working for me, I guess its problem with your url. 尝试为我工作,我想您的网址有问题。 Here i correct this, might be work for you. 我在这里纠正这个问题,可能对您有用。

JQuery JQuery的

var data = {
    name: $('.name').val(),
    crm_csrf_token: $('input[name="crm_csrf_token"]').val()
}

//Url should be index.php/YourControllerName/YourMethodName
var url = '<?php echo base_url(); ?>index.php/demo/signup';
$.ajax({
    url: url,
    dataType: 'json',
    type: 'post',
    contentType: 'application/json',
    data: data,
    success: function( data, textStatus, jQxhr ){
        console.log(data);
        console.log(textStatus);
        console.log(jQxhr);
    },
    error: function( jqXhr, textStatus, errorThrown ){
        console.log(jqXhr);
        console.log(textStatus);
        console.log(errorThrown);
    }
});

CI Controller : CI控制器

<?php

class demo extends CI_Controller {
    public function signup()
    {
            echo 'Hello World!';
    }
}

Greetings! 问候!

you just need to send csrf token via using jquery cookie you can download it from here https://github.com/js-cookie/js-cookie 您只需要使用jquery cookie发送csrf令牌,就可以从此处下载https://github.com/js-cookie/js-cookie

now in your ajax call 现在在您的ajax电话中

$.ajax({ $就({

url:url,
data:{
   "<?php echo $this->security->get_csrf_token_name(); ?>": Cookies.get('your_csrf_cookie_name_in_config')
    },
method :"POST",
success:function(data){
 $("#city").html(data);
}

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM