views:

1274

answers:

2

Again related with my weekend project, I'm trying to learn a bit more of web-development. So I'm putting in the list of features i want to implement, some stuff i absolutely have no idea how to do.

I've been reading tutorials on how to use ajax, but i can't find a simple one, that i can copy-paste (with one or two changes) to see it work before i go into the how it works.

What I've been searching is just a simple example on an ajax function, that triggers a mysql insert or update. Anyone as a simple example on how to do this? I think it would prove a nice start to learn it. (Ajax or Json are both ok).

Correct me if I'm mystaken: I'm basing myself on this tutorial. So as obviously the client side doesn't have access to database calls, what I should do, would be something like creating a code snippet to add stuff to the database right? For example create an "addcomment.php" that can be called with xhr.open(GET, "addcomment.php?comment=mycomment", true);

+1  A: 

Sounds like you got it right. Use Ajax to call a server side script which then does the database work for you.

Squeegy
A: 

A good setup is to use a framework like jQuery on the client side. This framework will encode and decode JSON automatically. On the server side you could create a class that handles all the ajax (or rather, ajaj, since we are using JSON) requests. Here is a short PHP file that shows the general idea. Add more elements to the functionMap array, and add the respective functions to the class.

class Ajaj{
    private $callback = "";
    private $functionMap = array( "select" => 'getIt');
    function Ajaj(){
     if(array_key_exists('jsoncallback',$_GET)){
      $this->callback=$_GET['jsoncallback'];
     }
    }
    function parse(){
     echo "$this->callback(";
     if(array_key_exists('action', $_POST)){
      $action = $_POST['action'];

      if(array_key_exists($action, $this->functionMap)){
       echo $this->functionMap[$action];
      }
     }else{
      echo "{}";
     }
     echo ")";
    }

    function getIt(){
      return json_encode(//get the database stuff here);
    }
}
$ajaj = new Ajaj();
$ajaj->parse();
Marius