403 Forbidden Access to CodeIgniter controller from ajax request

前端 未结 3 1480
离开以前
离开以前 2020-12-17 06:41

Im having trouble with sending an ajax request to codeigniter controller. It is throwing back a 404 Forbidden Access error. I have found some sort of similar question to thi

相关标签:
3条回答
  • 2020-12-17 07:16

    I was facing same problem but now I have fixed this problem.

    First of all, I have created csrf_token in header.php for every pages like below code

    $csrf = array(
                    'name' => $this->security->get_csrf_token_name(),
                    'hash' => $this->security->get_csrf_hash()
            );
    
    <script type="text/javascript">
        var cct = "<?php echo $csrf ['hash']; ?>";
      </script>
    

    After that, when we are sending particular value through ajax then we will have to sent csrf token like below code

    $.ajax({
        url:"<?php echo APPPATHS.'staff_leave/leaveapproval/getAppliedLeaveDetails'; ?>",
        data:{id:id,status:status,'<?php echo $this->security->get_csrf_token_name(); ?>': cct},
        method:"post",
        dataType:"json",
        success:function(response)
        {
            alert('success');
        }
    });
    

    I hope this code will help you because this is working for me.

    0 讨论(0)
  • 2020-12-17 07:26

    Remove the <code> and application/controller from your ajax_processor like,

    var ajax_processor = 'http://localhost/patientcare-v1/index.php/ajax_porcessor/save_physical_info';
    

    If you are hiding index.php from url by using htaccess or routing then try this url,

    var ajax_processor = 'http://localhost/patientcare-v1/ajax_porcessor/save_physical_info';
    
    0 讨论(0)
  • 2020-12-17 07:35

    CodeIgniter use csrf_protection, you can use it with Ajax and JQuery simply. This (ultimate ?) solution work on multiple Ajax request (no 403 ;-) and preserve the security).

    Change the configuration

    Open the file /application/config/config.php and change the line $config['csrf_token_name'] by :

    $config['csrf_token_name'] = 'token';
    

    You can use another name, but change it everywhere in future steps.

    Add CSRF in your Javascript

    Add script in a view; for me is in footer.php to display the code in all views.

    <script type="text/javascript">
        var CFG = {
            url: '<?php echo $this->config->item('base_url');?>',
            token: '<?php echo $this->security->get_csrf_hash();?>'
        };
    </script>
    

    This script create an object named CFG. This object can be used in your Javascript code. CFG.url contain the url of your website and CFG.token ... the token.

    Automatically renew the CSRF

    Add this code in your part $(document).ready(function($){---}) as

    $(document).ready(function($){
        $.ajaxSetup({data: {token: CFG.token}});
        $(document).ajaxSuccess(function(e,x) {
            var result = $.parseJSON(x.responseText);
            $('input:hidden[name="token"]').val(result.token);
            $.ajaxSetup({data: {token: result.token}});
        });
    });
    

    This script initialize the CSRF token and update it everytime when a request Ajax is sended.

    Send the CSRF in PHP

    I've created a new controller, named Ajax. In CodeIgniter, the link to use it is http://www.domain.ltd/ajax/foo

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Ajax extends CI_Controller {
    
        public function foo() {
            $this->send(array('foo' => 'bar'));
        }
    
        private function send($array) {
    
            if (!is_array($array)) return false;
    
            $send = array('token' => $this->security->get_csrf_hash()) + $array;
    
            if (!headers_sent()) {
                header('Cache-Control: no-cache, must-revalidate');
                header('Expires: ' . date('r'));
                header('Content-type: application/json');
            }
    
            exit(json_encode($send, JSON_FORCE_OBJECT));
    
        }
    
    }
    

    The send function add the CSRF automatically and transform an array in object.

    The final result

    Now, you can use Ajax with JQuery very simply !

    $.post(CFG.url + 'ajax/foo/', function(data) {
        console.log(data)
    }, 'json');
    

    Result :

    {"token":"8f65cf8e54ae8b71f4dc1f996ed4dc59","foo":"bar"}
    

    When the request get data, the CSRF is automatically updated to the next Ajax request.

    Et voilà !

    0 讨论(0)
提交回复
热议问题