2

As I'm developing my WebIDE, I keep coming up with questions that I cannot answer myself. This is because the project is supposed to help others create what they would "normally" create, but faster (i.e. as automated as possible). In this light, my question is how to you implement a PHP backend?

Here is what I do. I like to create "functions" that the client JavaScript can call. Usually, I send (via POST and JSON) a variable called "action" which holds the name of the "function" I am calling (as well as any arguments I wish to send it). The PHP code, then, looks something like this:

if(issset($_POST['action'])) {
    //function foo(arg1,arg2)
    if($_POST['action'] == 'foo') {
        $arg1 = $_POST['arg1'];
        $arg2 = $_POST['arg2'];
        //do stuff
    }
}

I can still reference other real functions I create in PHP, but I find that this is a nice way to organize everything and easy to implement in both JavaScript and PHP.

What do you do?

Edit 1: Ok, based on the first two answers to this question, I do not think I am explaining myself well.

I am asking how do you create a PHP back end. The idea is that you have your AJAX client written in JavaScript (or maybe something else, it doesn't matter), and then it will call your backend PHP with POST or GET data. Based on this data, your backend will do what it needs to do (maybe it will simply update the database, and maybe even return information, again: it doesn't matter).

The question now is: how do you tell it what to do? What do you send via POST/GET and how do you interpret it in your backend?

Community
  • 1
  • 1
Mike
  • 3,219
  • 23
  • 29

7 Answers7

2

I send all data to the backend in a big GET array.

actionpage.php?action=post&parameters[parameter1]=value1&parameters[parameter2]=value2

If you print_r($_GET), on the PHP side you'll see:

array(
    "action" => "create",
    "parameters" => array("parameter1"=>"value1","parameter2"=>"value2")
)

What this does is allow you to loop through your parameters. You can say in the pap

 if($_GET['action'] == 'create'){
      foreach($_GET['parameters'] as $key=>$value){ //something
Savas Vedova
  • 5,622
  • 2
  • 28
  • 44
Zeke Nierenberg
  • 2,216
  • 1
  • 19
  • 30
0

this website will answer all your ajax questions. I found it really helpful. http://ajaxpatterns.org/XMLHttpRequest_Call

Talha
  • 1,546
  • 17
  • 15
0

The question now is: how do you tell it what to do? What do you send via POST/GET and how do you interpret it in your backend?

Choose your own conventions. For example use an "action" value in your JSON data that tells the action, then add more parameters. You can spy on various websites's Ajax messages with Firebug extension in Firefox if you want to see what other websites do.

For example the Json POST data could be:

{
    action: "create",
    fields: {
       firstname: "John",
       lastname: "Doe",
       age: 32
    }
}

To which you could reply with the ID of the newly created record.

To delete the record:

{
    action: "delete",
    keys: {
        id: 4654564
    }
}

etc.

In the php ajax handler you could have something as simple as a switch:

$jsonData = Services_Json::decode($_POST['json']);
switch ($jsonData->action)
{
    case "save":
        if (validate_json_data($jsonData->fields))
        {
            UsersPeer::create($jsonData->fields);
        }
        break;
    case "delete":
        /* etc */
}

// return a json reply with 
$jsonReply = new stdClass;
$jsonReply->status = "ok";
$jsonReply->statusMessage = "Record succesfully created";
echo Services_Json::encode($jsonReply);
exit;

Javascript, say prototype Ajax.Request responder function will output the error message in a specially created DIV if "status" is not "ok", etc...

  • I do the same, but i target my javascript POST's to URL mappings instead of JSON, and i try to send as much plain HTTP POST stuff as i can. This way, you'll have the advantage of being able to use the same code also from a non-ajaxed trigger. (like a form submit) – SchizoDuckie Feb 15 '09 at 00:53
0

You need to organize functions? It's called 'class'.

/// todo: add error processing
$name=$_GET['action'];
$args=json_decode($_GET['args']); /// or just subarray, doesn't matter

/// 'Action' is constant here but in reality you will need more then one class for this
/// because you will want modules in your framework
if(method_exists('Action',$name))
    call_user_func_array(array('Action',$name),$args);
else { /* incorrect parameters processing */ }

/// Ajax-available functions are here
class Action
{
    public static function action1()
    {
        echo 'action1';
    }
    public static function action2()
    {
        echo 'action2';
    }
}
Toto
  • 89,455
  • 62
  • 89
  • 125
crimaniak
  • 123
  • 8
0

I use a front page controller which handles my routing. If you set up mod-rewrite you can have very clean endpoints where the first segment of your url refers to the controller (class) and then the subsequent segments would refer to the methods inside followed by the parameters being passed to the method.

http://domain.com/class/method/param1/param2

Manatok
  • 5,506
  • 3
  • 23
  • 32
-1

I do something very similar. What you need is a JSON object to pass back to the javascript. When you are done with your PHP, you can call json_encode to pass an object back to the front end. From there you can do more with it in Javascript or format it however you want.

There is more information on a similar question here: Best way to transfer an array between PHP and Javascript

Edit: After reading your edit, I think what you are doing is fine. When you send the AJAX request from Javascript include a variable like "action", or whatever youd like. From there you can check what the action is via a case and switch statement.

Community
  • 1
  • 1
barfoon
  • 27,481
  • 26
  • 92
  • 138
-3

I usually write the php functions as normal functions.

fn1(arg1, arg2){
 //do stuff here
}
fn2(arg3){
 //do stuff here
}

I pass the name of the function in a variable called action. Then do this:

foreach($_POST as $key => $value) 
$$key = $value;

To assign create variables of the same name as the arguments.

Then use a switch-case to call the appropriate function like so:

switch($action){
 case 'fn1':fn1(arg1,arg2);
 break;
 case 'fn2':fn2(arg3);
 break;
}

Is this what you are looking for?

Edit: You could use the PHP SOAP and XML-RPC extension to develop a webservice, where if you specify the function name in the SOAP request, that function will be automatically executed (you don't have to write the switch-case or if). I've used it in Java, but am not sure how exactly it works in PHP.

Anand
  • 7,654
  • 9
  • 46
  • 60
  • 2
    -1: trusting user input without any validation and working around the register_globals stuff are serious security issues. do not use this by any means for production code. – Karsten Nov 17 '09 at 20:31