Server-Side Functions with AJAX
Hey everyone. I’m trying to figure out the most efficient way to call a PHP function with jQuery. I thought you guys might be able to offer your own methods.
At the moment, I’m doing…
$.post(
'pageToLoad.php',
{ func: 'doSomething' },
function(results) {
console.log(results)
});
The $.Post Method
$.post accepts a total of four parameters:
- Url: Page to load
- Data: Key/value pairs to pass.
- Callback: Function to run after operation has completed.
- Type: Type of returned data
So let’s assume that ‘pageToLoad.php’ stored a bunch of functions, and we only wanted to call one specific method. Well, we could – as many have suggested on the forums – simply copy and paste that function into its own file, but this hardly seems efficient. What to do?
My Method
Now I could very easily be making this more difficult than it is. That’s why I’m curious as to how you handle these types of situations. I’ve been passing the function name as a key/value when we call the PHP page with jQuery.
{ func: 'doSomething' }
Then, from my PHP file (in this case, “pageToLoad.php”), I use the $_POST super-global to grab that value and execute it; like so:
// pageToLoad.php
// This will grab the value that was passed through - 'doSomething'.
// We then execute the function by appending the '()'.
$_POST['func']();
function someFunction() {
bla bla
}
function doSomething() {
echo 'hello world';
}
It Works!
This method works perfectly for my needs (with the obvious addition of some security checks). I’m only curious… how do you do it?