简体   繁体   中英

Ajax request with codeigniter forbidden

I'm trying to do an ajax request with jquery and codeigniter framework, but when I try to access to the server page, I have a forbidden access.

Here's my jquery code :

$('#btHello').click(function () {
    var name = $('#name').val();
        alert(name);
        $.ajax({
            type:'POST',
            data:'name='+ name,
            url:'<?php echo base_url();?>index.php/AjaxTest/ajaxtest',
            success: function(result, status){
                $('#result1').html(result);
            },

            error: function (result, status, error) {
                alert(error);
            }
        });
    });

The error alert just shows "Forbidden", nothing more.

Does anyone know what is the problem ?

Here's the controler :

class AjaxTest extends CI_Controller {

    public function index() {
        $this->load->view('home/head');
        $this->load->view('home/nav');
        $this->load->view('test/ajaxTest');
        $this->load->view('home/foot');
    }

    public function ajaxTest(){
        $name = $this->input->post('name');
        echo 'Hello '.$name;
    }
}

Send

$this->security->get_csrf_token_name() : $this->security->get_csrf_hash()

with the request. hope it'll solve your problem

$.ajax({
    url: "<?php echo site_url().'/admin/getNewLocations' ?>",
    type: "POST",
    data: {
        func: 'getNewLocations',
        '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
    },
    success: function(data) {
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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