0
votes

In my bootstrap.php I have the following code:

// Check if ajax request
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest")
{
    Route::set('ajax', '(<controller>(/<action>(/<id>)))')
    ->defaults(array(
        'controller' => 'home',
        'action'     => 'index',
    ));
}

Route::set('default', '(<controller>(/<action>(/<id>)))')
    ->defaults(array(
        'controller' => 'home',
        'action'     => 'index',
    ));

The 'ajax' route is incomplete. What I want to do is if the request is done via. ajax, then Kohana should look for the controller in a subfolder within my controllers called ajax/. So, if ajax request then:

http://localhost/myproject/somecontroller/someaction routes to somecontroller inside the ajax subfolder. If not ajax then just use the 'default' route.

2

2 Answers

2
votes

Use a lambda/callback function/method something like this:

Route::set('ajax', function($uri)
    {
        if (Request::$current->is_ajax() AND $params = Route::get('default')->matches($uri))
        {
            $params['directory'] = 'ajax';
            return $params;
        }
    },
    '(<controller>(/<action>(/<id>)))'
);

See http://kohanaframework.org/3.2/guide/kohana/routing and http://kohanaframework.org/3.2/guide/api/Route

1
votes

Try this:

Route::set('ajax', '(<controller>(/<action>(/<id>)))')
->defaults(array(
    'directory'  => 'ajax',
    'controller' => 'home',
    'action'     => 'index',
));

However, personally, I'd handle both AJAX and non-AJAX requests in the same controller, using Request::current()->$is_ajax to tell if it was an AJAX request. The AJAX behavior is probably not significantly different to the non-AJAX, so it might be beneficial to keep both in the same controller. You may end up with code duplication if you handle AJAX requests in a different controller.