How to run multiple ajax calls on one page

If I create an "ajaxified" user interface with many ajax calls to create, rename, delete various things on my page - what is the best way to handle all these "codes behind" ajax pages? At first, I had a different .php file for each call (i.e. Candy_Rename.php, Candy_Delete.php). But I found that my code base is becoming overwhelming with the number of files created.

Now I send the “command” parameter with my request, and then I manage all the things related to Candy in a single file “ajax_Candy.php”. So, for example, my jQuery query would look like this:

$.get('ajax_Candy.asp', { command: 'insert', candyName: 'Jolly Ranchers' }, function (response) {
    alert(response.candyId);
}

Is this a good way to do this?

Edit: All answers were excellent and said almost the same thing. I had to choose one, and I thought that the mention of safety is important for everyone who travels along this path - so you go. I use the switch statement as one of the mentioned users.

+2
source share
3 answers

Assuming you are working with server-side security issues, I don't see a problem with your method. The PHP file must make sure that the requestor has the privilege to execute the command. You do not want the user to delete all your entries ...

+2
source

, , , . , . switch , .

switch($_GET[command) 
{ 
  case 'insert' : do insert stuff; break;
  case 'delete' : do delete stuff; break;
}
+2

Yes, that’s better. There is nothing wrong with a large number of files, however you should strive to maintain interconnected functionality together - high cohesion.

But don't go overboard, and let one php file handle more than just Candy. If you start looking for duplicate code among your php files, start subclassing.

0
source

All Articles