This is my typical solution, so YMMV.
For the PHP end, I break my various remote functions into individual files (e.g. 'add_user.php', 'login.php', 'do_something.php'), each of which sets response data into a pre-defined array named 'response', and include the files dynamically based on the action requested, such as:
switch ($_POST['action']) {
case 'addUser':
require 'add_user.php';
break;
case 'login':
require 'login.php';
break;
// ... snip ...
default:
$response['result'] = 'badaction';
break;
}
echo json_encode($response);
Each individual file is designed to parse an HTTP POST request, do something with it, and return a JSON response (this gives both sides a fairly simple time parsing results, since PHP will automatically prepare the POST values for you, and jQuery can automatically convert a JSON response into an object, though I recommend picking up the JSON2 library from json.org so you don't have to worry about eval()
issues), and they look something like this:
<?php
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
die; // prevent the file from being accessed directly
}
// the do {} while(0); block allows us to set the response and then short-circuit
// execution without using a big ugly nest of if/else statements or a function
do {
if (!isset($_POST['something'],$_POST['parameter'],$_POST['whatever'])) {
$response['result'] = 'badinfo';
continue;
}
// ... snip ...
} while(0);
Given jQuery's fairly simple AJAX request methods, the JS shouldn't be too hard to figure out. One nice thing about this method is that, should you need the response to be in some other format (XML, URLEncoded, etc), it's a snap; personally, I add a 'format' parameter to the request and parse it like so:
// EXPLICIT FORMAT
$format = strtolower(isset($_REQUEST['format']) ? $_REQUEST['format'] : null);
// IMPLICIT FORMAT
if (!$format) {
if (isset($_SERVER) && is_array($_SERVER) && array_key_exists('HTTP_ACCEPT',$_SERVER)) {
$accept = $_SERVER['HTTP_ACCEPT'];
if (stripos($accept, 'application/json') !== false || stripos($accept, 'text/javascript') !== false) {
$format = 'json';
}
}
if (!$format) {
$format = 'url';
}
}
switch ($format) {
case 'json':
echo json_encode($response);
break;
case 'url':
default:
echo http_build_query($response);
break;
}
Hope this helps, reply in comments with any questions and I will hopefully shed some more light on the situation.