Reputation: 307
I have no problem creating an AJAX call, but each url must at the moment be unique. I wish to contain multiple PHP functions within the same file, and specifically access one of the PHP functions with a particular AJAX call.
Using jQuery, at the moment I am passing the .data parameter with an integer specification, then using the $_GET method in the PHP file and running the proper function specified by the integer.
How can I do this better? I want to call a specific function amongst many in a PHP file; I do not want to have individual files for each function
Upvotes: 2
Views: 725
Reputation: 22817
I could tell you to go with the quick and dirty solution, i.e. passing a function
param in the call, then:
switch($_GET['function'])
{
case 'show':
show();
break;
case 'delete':
delete();
break;
case 'awesome':
awesome();
break;
}
But this is totally unmaintainable, because you will drown into a mess of includes, or even worse into a huge column of code you won't be able to reuse anywhere.
I advice you to get into routing, i.e. setting up a relationship between the URLs being pointed at, and functions being called, making use of parameters if needed [like in the second example below]:
/users --> printAllUsers
/users/123 --> printUser($id)
/products/beers --> printProducts($category)
/search --> search()
...
This way you are decoupling the routing itself from the response generation: you can find a better overall explanation here, then you can find a very good an thin library here you can use in your projects without relying on a whole framework.
Ah, before getting in buzzword oceans with thing like OOP, MVC, RESTful service - which all deserve to be learned of course - stick with this first concept: it was the one I really missed when I began learning all this stuff, and it was the eureka for me.
Upvotes: 1
Reputation: 39704
You can assign each function an ID
, send the AJAX
GET
based on one ID
and call that function with switch
eg: Send GET = 1
, or GET = 2
switch ((int)$_GET['id']) {
case 1:
processData();
break;
case 2:
sendEmail();
break;
case 3:
restoreBackup();
break;
// ........ and so on
}
Upvotes: 1