18

I have been looking into backbone.js and I can't seem to figure out how to get it communicate with php in order to save the models data. It sends a request but how do I capture that request whether it be "Create", "Update", "Read", "Delete" etc.

Thanks

brenjt
  • 15,997
  • 13
  • 77
  • 118

4 Answers4

15

Another option you may consider is to roll with a pre-packaged RESTful framework that has all the necessary functions built in to execute your Backbone server queries. My personal favorite is Josh Lockhart's SlimPHP Framework.

Some simple sample code (once you have SlimPHP setup) used to take your Backbone calls look like this.

$app->get('/user', function() use ($app) {

    // See if session is set, get user info as array
    if (isset($_SESSION['userID']) {
         $user = // grab user with userID data from DB
    }

    // Respond to the get request with a json object
    $response = $app->response;
    $response['Content-Type'] = 'application/json';
    $response->body(json_encode($user));
}

Here is a POST example that turns Backbone json into arrays.

// Middleware that detects type of data and converts it to something usable
$app->add('Slim_Middleware_ContentTypes');    // JSON to associative array

...

$app->post('/message', function() use ($app) {
    $dataIn = $app->request()->getBody();

    ...

    // Save to DB $dataIn['message'], $dataIn['author'], etc.
}

Here is a PUT example using some parameters.

$app->put('/user/:id', function($id) use ($app) {

    // Find appropriate user from DB that has $id as ID

    $dataIn = $app->request()->getBody();

    // Save to DB $dataIn['name'], $dataIn['age'], etc.
}

And here is a DELETE.

$app->delete('/message/:id', function($id) use ($app) {

    // Find appropriate message from DB that has $id as ID

    // Delete message with id of $id
}

While this isn't an exhaustive example of all the other things to consider, it should give you an idea of the kinds of open solutions already out there for you to use. I personally like Slim because it is so lightweight, simple, yet it has all the features you'd want in a RESTful server. Great for prototyping. Combine it with a DB abstraction layer and some other tools and you can make just about anything you want quicker.

You can see some other sample code along these lines here:

  1. How to post Backbone model to server
  2. Ways to save Backbone data

And here is a link to some other PHP based RESTful solutions: Framework List

Community
  • 1
  • 1
jmk2142
  • 8,581
  • 3
  • 31
  • 47
8

The model of backbone.js uses specific urls for fetch and send data. You have to make sure, to have a php script called there.

Now there are two possibilities.

First, the method is send inside the $_POST as additional variable. Second, you have to look for the used request method(GET,POST,PUT,DELETE) which you can with $_SERVER['REQUEST_METHOD']

Now you can use simple if-else or switch statements to handle the request and deliver the needed data as i think json.

edorian
  • 38,542
  • 15
  • 125
  • 143
Flyingmana
  • 305
  • 2
  • 13
  • Okay, now from looking at the Backbone.js API it looks like with the ajax request it sends data which is a stringified model. How do I get that information? $_SERVER['model'] or something similar? – brenjt Jun 01 '11 at 22:41
  • Or I guess my question is how can I access the data of the model being saved with Backbone? Or does it even get passed with the Ajax request? – brenjt Jun 01 '11 at 22:51
  • I was able to obtain the JSON encoded model string with `$GLOBALS['HTTP_RAW_POST_DATA']` Is it safe to do it that way or not? – brenjt Jun 01 '11 at 22:58
  • It is better to do $rawPost = file_get_contents("php://input"); See http://us.php.net/manual/en/wrappers.php.php – Rafa Oct 27 '11 at 15:16
  • Is there any reason you made your answer community wiki? You know that you won't acquire rep from the upvotes? Would you like me to undo this? – Kev Oct 29 '12 at 23:55
  • I dont care about rep that much, also I belive that a community wiki answer is better then no answer at all. You see this Answer is not very big, I am not an expert for this, so its better when other people can extend it. – Flyingmana Dec 13 '12 at 11:55
3

$GLOBALS['HTTP_RAW_POST_DATA'] works fine for me, i don't know for what reason print_r($_POST) doesn't print anithing!!

Gabriel
  • 1,890
  • 1
  • 17
  • 23
  • Yeah I noticed that ` print_r($_POST) ` didn't do anything and I found that `$GLOBALS['HTTP_RAW_POST_DATA']` contained what I needed – brenjt Jun 02 '11 at 01:18
  • i was looking this link http://stackoverflow.com/questions/5755074/a-restful-persistence-solution-usable-with-backbone-js-in-php but i didn't understand. – Gabriel Jun 02 '11 at 01:20
2

In your php script you will have this for the PUT and DELETE methods as you can filter those with: $_SERVER['REQUEST_METHOD']

parse_str(file_get_contents("php://input"),$post_vars);

If the request is POST or GET you can use it normally but if the request is PUT or DELETE so use the above line and so you can access to the vars with:

$post_vars['fruit'] for example...

When you are ready to answer to backbone, you only have to first make the correct header:

header('Content-type: application/json; charset=utf-8');

and encode you answer with json:

echo json_encode(array("message"=>"missing fields","status"=>200));
manuelpgs
  • 1,283
  • 1
  • 14
  • 20