This is my first in a line of tutorials based on Kohana PHP Framework. This first tutorial is based on how to use Kohana in conjunction with AJAX. Some people have had some trouble with it, as did I when I first used it, so here are the basics.

I’m assuming you know how to set up kohana & have a project set up with a new controller. All you need to do is create a new method in your controller. The trick is to disallow unauthorised access, that is access for anyone or anything, but AJAX requests. Here is a basic Kohana controller:

class Test_Controller extends Template_Controller {

    function index() {
        //code for your front page
    }

    function ajax() {
        //code that your AJAX request should execute
    }

}

That is a basic Kohana controller (in this case an extention of the Template Controller). I’ve also added the method that will be used for the AJAX functionality. To use it all you would have to do is tell your AJAX request to visit example.com/test/ajax. Here is the structure for that request domain.name/controller/method or you could use Kohana’s built in url builder by writing echo url::site('controller/method');. You or anyone else can also access it via URL at the minute & you probably don’t want that, so let’s see how to prevent that.

There is an exceptionally simple way to do this, as mentioned by Thomas in his comment. Just use Kohana’s built in request helper:

if(request::is_ajax()) //do stuff

This runs a check for the HTTP header HTTP_X_REQUESTED_WITH and makes sure it equals xmlhttprequest. That is how it determines if the call came via AJAX. It is compatible with all modern browsers.

There is one problem with any HTTP header check & that is that HTTP headers can be faked. My best advice for protecting again misuse of AJAX requests is to make sure any AJAX requests that directly access a database have their queries checked, double checked, and triple checked for possible attacks and are also sanitised properly.