tags:

views:

247

answers:

2

Hey

I'm working on converting my standard PHP project to OOP but I ran into a wall about how to handle AJAX calls with PHP Classes. I'm not happy with the way I'm doing this now. I have a TillAjax.php file which I call from my TillUI.php file from a AJAX call.

In the TillAjax.php file I do this to get the information passed from the ajax call.

$till = new Till();
if(isset($_POST['data']))
    $till->doStuff($_POST['data']);

I think this ruins the OOP.

I have worked with ASP.NET MVC and here its possible to call a specific action in a controller without i have to check for the post value. So I want to know if there is a smarter PHP way to solve the above problem?

+2  A: 

The method I use for this is to have an Ajax class.

Your php file calls Ajax::Process($_GET['handle']), where 'handle' contains the name of a static class method, so perhaps 'Till::Process'. The Ajax class checks the function against a list of permitted functions (i.e. functions that you are allowing to be called via ajax), and then uses call_user_func_array to call the function (my code uses the contents of $_POST as arguments to pass to the function). The return of that function is automatically encoded as json and outputted to the client.

This means that your target php file looks like this:

<?php

//File: ajax.php

include ("Ajax.php");

Ajax::Process($_GET['handle']);

?>

Which I think is pretty simple.

Then you can have javascript that looks like this (jquery) :

$.get('ajax.php?handle=Till::Process', {}, function(result) {
  //called on page response
});

So then result now contains whatever data is returned from the php method Till::Process.

Kazar
+1  A: 

Have you considered using a PHP MVC framework such as CodeIgniter, CakePHP, Kohana, etc? They will let you route requests to specific controller methods. It will be a much cleaner solution if migrating to one of these frameworks is an option for you.

Justin Ethier