Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is my typical solution, so YMMV.</p> <p>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:</p> <pre><code>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); </code></pre> <p>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 <a href="http://www.json.org" rel="nofollow noreferrer">json.org</a> so you don't have to worry about <code>eval()</code> issues), and they look something like this:</p> <pre><code>&lt;?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); </code></pre> <p>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:</p> <pre><code>// EXPLICIT FORMAT $format = strtolower(isset($_REQUEST['format']) ? $_REQUEST['format'] : null); // IMPLICIT FORMAT if (!$format) { if (isset($_SERVER) &amp;&amp; is_array($_SERVER) &amp;&amp; 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; } </code></pre> <p>Hope this helps, reply in comments with any questions and I will hopefully shed some more light on the situation.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload