using jquery $.ajax to call a PHP function
Use $.ajax
to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:
$.ajax({ url: '/my/site', data: {action: 'test'}, type: 'post', success: function(output) { alert(output); }});
On the server side, the action
POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:
if(isset($_POST['action']) && !empty($_POST['action'])) { $action = $_POST['action']; switch($action) { case 'test' : test();break; case 'blah' : blah();break; // ...etc... }}
I believe that's a simple incarnation of the Command pattern.
I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php
After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.
For ease of use reference the function in a simple manner:
var P = $.fn.php;
Then initialize the plugin:
P('init', { // The path to our function request handler is absolutely required 'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php', // Synchronous requests are required for method chaining functionality 'async': false, // List any user defined functions in the manner prescribed here // There must be user defined functions with these same names in your PHP 'userFunctions': { languageFunctions: 'someFunc1 someFunc2' }});
And now some usage scenarios:
// Suspend callback mode so we don't work with the DOMP.callback(false);// Both .end() and .data return data to variablesvar strLenA = P.strlen('some string').end();var strLenB = P.strlen('another string').end();var totalStrLen = strLenA + strLenB;console.log( totalStrLen ); // 25// .data Returns data in an arrayvar data1 = P.crypt("Some Crypt String").data();console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
Demonstrating PHP function chaining:
var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();console.log( data1, data2 );
Demonstrating sending a JSON block of PHP pseudo-code:
var data1 = P.block({ $str: "Let's use PHP's file_get_contents()!", $opts: [ { http: { method: "GET", header: "Accept-language: en\r\n" + "Cookie: foo=bar\r\n" } } ], $context: { stream_context_create: ['$opts'] }, $contents: { file_get_contents: ['http://www.github.com/', false, '$context'] }, $html: { htmlentities: ['$contents'] }}).data(); console.log( data1 );
The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.
I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).
You basically send a JSON string in a specific format to the server, e.g.
{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}
which includes the function to call and the parameters of that function.
Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.
This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.