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
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.
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:
And here is a link to some other PHP based RESTful solutions: Framework List
$GLOBALS['HTTP_RAW_POST_DATA'] works fine for me, i don't know for what reason print_r($_POST) doesn't print anithing!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With