A
A
Alexander2016-01-04 20:58:36
JavaScript
Alexander, 2016-01-04 20:58:36

How to correctly pass parameters via Ajax to Kohana action?

It is necessary to pass parameters from jQuery to the kohana controller in order to make page navigation on the page, records must be loaded via Ajax.

How to correctly set the path in the bootstrap.php file to the required controller, so that it can receive two get parameters at once? Parameters: lines - number of records, pages - number of pages.

Kohana version - 3.1.4
Controller side code:

// Ajax функция - возвращает список таймеров (путь - timerslist)
    public function action_timers_list_ajax(){


            // данные из GET запроса       
            $lines = (int) $this->request->query('lines');
            $pages = (int) $this->request->query('pages');

            $data = array(
                'lines'    => $lines,
                'pages'  =>  $pages
            );
       
            // var_dump($data); 

            json_encode($data);
            exit;      

    }

Now the code in the bootstrap.php file for the timers_list_ajax action looks like this:
Route::set('timerslist', 'timerslist(<controller>(/<action>(/<id>)))')
->defaults(array(
            'directory'  => 'index',
            'controller' => 'timer',
            'action' => 'timers_list_ajax',     
));

How to correctly specify lines and page parameters instead of id?

$.ajax({    
    type:"GET",
    url: "my_project/timerslist",  
    data: {"lines": 10, "pages": 1},
    contentType: 'application/json',
    dataType: "json"
}).done(function(response){         
console.log(response);
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan, 2016-01-04
@dohlik

You are confusing router parameters with query string ($_GET) parameters, which are not specified in routing at all and can be any or absent. In this particular case, the id in the route is not needed. And the lines and pages parameters must be retrieved from the request via $this->request->query(), something like this:

$data = array(
        'lines'    => (int)$this->request->query('lines') ?: 10,
        'pages'  => max(1, (int)$this->request->query('pages')),
    );

Although I would use the more common options like offset/limit or page/perpage. More understandable names, IMHO.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question