I am implementing Backbone.js with Codeigniter, and having a hard time receiving a proper response from Codeigniter upon a Ajax call. I was doing a #Create, which led to #save, and then #set, right at there, it breaks and couldn't find the ID in the format I returned the data.
For testing purpose, I'm echo-ing
'[{"id":"100"}]'
right back to the browswer, still it couldn't find it.
Anyone aware of a Backbone/Codeigniter(or similar) RESTful implementation example?
You need to return 200 response code or it would not pass as good response.
I built few apps with Backbone/CI combo and it is much easier if you use Phil Sturgeon's REST implementation for CodeIgniter
Than you controller that is located at url example.com/api/user and directory applications/controllers/api/user.php would look something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
include APPPATH.'core/REST_Controller.php'; // MUST HAVE THIS LINE!!!
class User extends REST_Controller {
// update user
public function index_put() // prefix http verbs with index_
{
$this->load->model('Administration');
if($this->Administration->update_user($this->request->body)){ // MUST USE request->body
$this->response(NULL, 200); // this is how you return response with success code
return;
}
$this->response(NULL, 400); // this is how you return response with error code
}
// create user
public function index_post()
{
$this->load->model('Administration');
$new_id = $this->Administration->add_user($this->request->body);
if($new_id){
$this->response(array('id' => $new_id), 200); // return json to client (you must set json to default response format in app/config/rest.php
return;
}
$this->response(NULL, 400);
}
// deleting user
public function index_delete($id)
{
$this->load->model('Administration');
if($this->Administration->delete_user($id)){
$this->response(NULL, 200);
return;
}
$this->response(NULL, 400);
}
}
It will help you to return proper responses.
TIP: Also whatever you return to client will be set to model attributes. E.g. when creating user if you return only:
'[{"id":"100"}]'
model will be assigned id 100. But if you return:
'[{"id":"100", "date_created":"20-aug-2011", "created_by": "Admin", "random": "lfsdlkfskl"}]'
all this key value pairs will be set to user model (I added this just for clarity, since it confused me in start)
IMPORTANT: this is for CI 2.0+ if you are using 1.7.x REST implementation is a tiny bit different that concerns directory structure
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