views:

177

answers:

1

Whats the best way to call a certain method in a PHP file with Ajax.Request (using prototype)? I am submiting a form with Form.serialize, so I thought of adding a parameter (like the name of the method to call) and then check it on the server script. Something like:

var params=Form.serialize("someform")+"&=method='check_data'";
new Ajax.Request('somescript.php',{method:'post',parameters:params,onSuccess:
function(response)
{ 
    .. do something with the response

And in somescript.php:

if($_POST["method"] == "check_data")
{
    check_data();
...
}

This would work, but Im sure theres a better or simpler way to call a remote method (ala MVC). Any ideas?

+3  A: 

Under no circumstances do this for normal PHP methods. It opens a big potential security hole. Even if you limit the commands that can be called that way, it's not a good way to go in the long run.

Either stay with what you already do: Define a list of commands that can be passed to the PHP script (e.g. command=delete, command=update, command=copy, whatever you need), and call them using switch.

Or use a class with methods that can be safely called from outside:

class myCommands
{
  function copy()  {  ... }
  function delete()  {  ... }
  function update()  {  ... }
 }

then, in the PHP file, pass through the command like

if (method_exists($class, $_POST["method"]))  
 call_user_func(array($class, $_POST["method"]));
Pekka
You suggest the solution I posted but without passing the method name as parameter (something else like update, copy) and then check it on the php script and call the method I want?
JoaoPedro
Nice! Thanks a lot!
JoaoPedro
Your solution is fine because it limits the range of functions that can be called. If you want to introduce a wildcard (i.e. direct calling of whatever is in `$_POST["method"]` I suggest doing this for the methods of a class name only as I show in my updated answer; otherwise it would be possible to execute any PHP function.
Pekka
Didn't see your last comment. You're welcome!
Pekka