简体   繁体   English

带有 codeigniter 403 的 Ajax 请求(禁止)

[英]Ajax request with codeigniter 403 (forbidden)

I'm trying to send an value with Ajax to Controller file in Codeigniter but without success.I have searched for that problem and i now this question is made many times here,but still can't find a sultion.Hope anyone can help me.我正在尝试使用 Ajax 向 Codeigniter 中的控制器文件发送一个值,但没有成功。我已经搜索过这个问题,我现在这个问题在这里提出了很多次,但仍然找不到解决方案。希望任何人都可以帮助我. Thanks !谢谢 !

Js file. .js 文件。

function submitSend()
{
    var message = $('#sms').val();
    if(message == "")
    {
      $("#sms").attr("placeholder", "Type a message please...");
      return false;
    }

    $.ajax(
    {
      url: "<?php echo base_url();?>/mychat/send",
      type: 'POST',
      data:{
              '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
              'message': message
             },
      success: function (data)
      {
       window.console.log('Successful');
      },
      error :function(data)
      {
      window.console.log('Failed');
      }
    });
}

Controller function.It's in file called MyChat.控制器功能。它在名为 MyChat 的文件中。

public function send()
  {
     $message = $this->input->post('message');
     echo $message;
  }

Add this code in your footer view before including JS file在包含 JS 文件之前在页脚视图中添加此代码

<?php $CI =& get_instance(); ?>
<script> 
    var csrf_name = '<?php echo $CI->security->get_csrf_token_name(); ?>';
    var csrf_hash = '<?php echo $CI->security->get_csrf_hash(); ?>';
</script>

and just call these variables anywhere you need like this只需像这样在您需要的任何地方调用这些变量

data:{
     csrf_name : csrf_hash,
     'message': message
},

I'm afraid you can't use PHP tags in JavaScript files, as you've mentioned you have a JS file.恐怕你不能在JavaScript文件中使用PHP标记,因为你已经提到你有一个JS文件。

You must run your PHP codes in .php files.您必须在.php文件中运行您的PHP代码。

Perhaps you can decouple your submitSend() function a bit and make it more modular by extracting the PHP tags as well as $('#sms').val() .也许您可以通过提取PHP标记以及$('#sms').val()submitSend()函数稍微解耦并使其更加模块化。 These can be passed to the function as parameters from where you call it ( .php files) .这些可以作为参数从您调用它的位置.php文件)传递给函数。

很可能是因为 CSRF 令牌尝试禁用 csrf 并检查它是否由于 csrf 然后将 csrf 配置中的特定功能列入白名单

This work for me.这对我有用。

/app/Config/Security.php /app/Config/Security.php

/**
     * --------------------------------------------------------------------------
     * CSRF Token Name
     * --------------------------------------------------------------------------
     *
     * Token name for Cross Site Request Forgery protection cookie.
     *
     * @var string
     */
    public $tokenName = 'csrf_token_name';

Inside my form在我的表格里面

<input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>" />

in the script.js在 script.js 中

var tokenHash=jQuery("input[name=csrf_token_name]").val();
$.ajax({
  method: "POST",
  url: "/somecontroller",
  data: { name: "John", location: "Boston" },
beforeSend: function (xhr) 
        {       
        xhr.setRequestHeader('X-CSRF-Token' , tokenHash);       
        },
})
  .done(function( msg ) {
    console.log( "Data Saved: " + msg );
  });
    

For Codeigniter 4对于 Codeigniter 4

First, go to app/Config/Security.php首先,进入app/Config/Security.php

change改变

public $regenerate = true;

To

public $regenerate = false;

Note: Changing $regenerate to false is not good practice.注意:将$regenerate更改为 false 不是好的做法。

Second, go to app/Config/Routes.php create your rout that you will call to preform request.其次,转到app/Config/Routes.php创建您的路由,您将调用该路由来进行预执行请求。

$routes->post('url', 'ControllerName::FunctionName');

Then make sure u added csrf_token() and csrf_hash() to data you want to send.然后确保您将csrf_token()csrf_hash()添加到要发送的数据中。

So the code will look like this:所以代码将如下所示:

var data= {
    "<?= csrf_token() ?>" : "<?= csrf_hash() ?>",// make sure this line exists
    something: "Something"
};

$.ajax({
        url: "<?= base_url('url_in_routes') ?>",
        type: "POST",
        data: data,
        headers: {'X-Requested-With': 'XMLHttpRequest'},
            
        success: function (response){
            console.log("success");
                
        },
        error: function(xhr, status, error) {
            console.log("Error: " + error);
              
        },
        complete: function(data) {
            console.log(data.statusText);
        }
});

Controller:控制器:

class Test extends BaseController{
    
    public function handleAjaxRequest(){
        $something = $this->request->getPost('something');
        // Now u can use $something to save it to ur DB or do what you want.
    }
    
}

You can't use php tag in js file您不能在 js 文件中使用 php 标签

url: "<?php echo base_url();?>/mychat/send", //this line in js file is wrong

You only use php tag in script tag in .php file like this您只能在 .php 文件中的脚本标记中使用 php 标记,如下所示

<script>
 // ... some code here 
     url: "<?php echo base_url();?>/mychat/send",
 // ... some code here
</script>

Or add this line in header html或者在标题 html 中添加这一行

<script> 
    var BASE_URL = '<?php echo base_url(); ?>';
</script>

and use it in js file并在js文件中使用

....
url: BASE_URL+"mychat/send",
....

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

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