MikeMurko
MikeMurko

Reputation: 2233

How to run multiple ajax calls on one page

If I'm making an 'ajaxified' user interface with many ajax calls for creating, renaming, deleting various things on my page - what is the best way to handle all those "code 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 my code base becoming overwhelming with the number of files created.

Now I'm sending a "command" parameter with my request, and then I manage all things related to Candy in one file "ajax_Candy.php". So for example my jQuery request will be:

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

Is this a good way to go about it?

Edit: All of the answers were great and said pretty much the same thing. I had to pick one and I thought mentioning security is important for anyone else who travels down this path - so there you go. I am using the switch statement as one user mentioned.

Upvotes: 2

Views: 1991

Answers (3)

jontyc
jontyc

Reputation: 3495

Yes, that is better. There is nothing wrong with lots of files, however you should be striving to keep related functionality together--high cohesion.

But don't go overboard and let the one php file handle more than just Candy. If you start to find code duplication amongst your php files, start subclassing.

Upvotes: 0

Raisen
Raisen

Reputation: 4495

Assuming that you are handling security issues on the server side, I don't see a problem with your method. The PHP file has to make sure that the requester has privilege to execute the command. You wouldn't want an user deleting all of your records...

Upvotes: 2

paishin
paishin

Reputation: 21

Sure, what you are doing now is a much better aproach. Just have one file that controlls all actions. I usually use a switch statement on command to keep everything nice and clean.

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

Upvotes: 2

Related Questions