Samira Yaqoub
Samira Yaqoub

Reputation: 3

controller not sending data codeignitter

I have a ready ci application and I am trying to use ajax but even I tried many correct codes the get works but the post never I think there is some problem with config ajax_test view

<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
   var base_url = "<?=base_url()?>";
   $(document).ready (function(){
    $('#get_bt').click(function(){
        $.post(base_url+'ajax_test/info_page' , {name:'bashir' , id:'1'}, function(data){
            alert(data);

        })
        });
});

<button id="get_bt">get</button>

controller

<?php
 class Ajax_test extends CI_Controller {
 public function index(){
    $this->load->helper('url');
    $this->load->view("ajax_test");

}
public function info_page(){
    echo $this->input->post('name');
}
}   
?>

Note it works with get instead of post The jquery error

Failed to load resource: the server responded with a status of 403 (Forbidden)

Upvotes: 0

Views: 56

Answers (2)

DFriend
DFriend

Reputation: 8964

The 403 error is because of a configuration setting. In the file /application/config/config.php you have the following setting.

$config['csrf_protection'] = TRUE;

Which is a good thing but also requires that you send the CSRF token name/value to the controller along with the 'name' and 'id'.

Check out the documentation on Cross-site request forgery (CSRF) to learn how to get those values.

Or you can use GET as another answer suggested. (GET doesn't check CSRF.)

Or you can use $config['csrf_protection'] = FALSE; (Generally a bad idea.)

Or you can whitelist the URI using the following in /application/config/config.php

$config['csrf_exclude_uris'] = array('ajax_test/info_page');

But sending the CSRF credentials is the most secure and therefore best solution.

Upvotes: 2

Janessa Bautista
Janessa Bautista

Reputation: 294

try to use

$name = $_GET['name'];

echo $name

instead of using input->post

or change your ajax to

$.ajax({
        url: your url,
        type: "POST",
        data: {name:"bashir"},
        dataType: "json",
        contentType: false,
        cache: false,
        processData: false,
        success: function(data) {
            alert("success")
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("Error");
        }
    });

Upvotes: 0

Related Questions