0

I have a service running for static pages on CodeIgniter and now I want to make it dynamic using Ajax calls, but the Ajax call always returns as 404 error (defined by the alert on the error section). The index method of the controller is accessible. Only the _get_procs method returns 404.

My Javascript:

$(document).ready(function(){
    base_url = '<?= base_url() ?>';
    $('#btnAjax').click(function(){
        alert("AJAX");
        $.ajax({
            url: base_url + 'general-data/_get_procs',
            type: 'POST',
            data: {'period': '1'},
            dataType: 'json'
        }).success(function(response){
            alert(response);
        }).error(function(e){
            alert("Error");
        });
    });
});

My Controller:

function _get_procs(){
    $period = $this->input->post('period');
    echo json_encode("OK");
}
Minoru
  • 1,680
  • 3
  • 20
  • 44
  • 1
    can you rename your function to getprocs() and see if that works instead? Codeigniter has a weird settings that forbids underscores in function names sometimes. – Dimi Mar 10 '17 at 17:16
  • What a joke! It worked, @Dimi. Is there a way to work around this underscore problem? – Minoru Mar 10 '17 at 17:20
  • 2
    There is, but i have absolutely no idea where it is. I have been avoiding underscores in function names just in case someone wants to reuse any of my stuff and does not have that setting turned on. (kind of like php short tag `` thing). If you find it, can you post it as an answer to this question? Thanks :) – Dimi Mar 10 '17 at 17:23
  • Show contents of your routes.php, problem may be there. – cssBlaster21895 Mar 10 '17 at 20:20
  • @cssBlaster21895 There is no rule related to the Controller itself. – Minoru Mar 10 '17 at 21:08
  • 1
    aah, the underscore before the name of function is the convention used for private function https://www.codeigniter.com/user_guide/general/styleguide.html#private-methods-and-variables – cssBlaster21895 Mar 10 '17 at 21:16

1 Answers1

1

Comments from @Dimi showed me what was going on: the use of underscores on the start of functions' names, e.g. _function_one doesn't work; function_one does work, makes CodeIgniter break.

The solution I came up with was to rename the function to the format function_one (get_procs, on my case) and create a rule on the routes.php config file:

$route['controller/_get_procs'] = 'controller/get_procs';

This is a workaround to make it work without changing the default configuration of CodeIgniter. I don't know if there is another way.

As pointed out by @cssBlaster21895, CodeIgniter follows up PHP Coding Style (see more here), which determines _function as a private function.

Minoru
  • 1,680
  • 3
  • 20
  • 44