ajax - codeigniter: Rest api + Json -
how, implement code igniter rest api outputs ajax outputting json. i'm unsure how use rest api deleting , adding json. how delete item json , database.
1. rest api routing
let's start routing of api - if apply best practice api want use http verbs (post/put/get...). (read more on http verbs , rest here)
if on codeigniter 2.x read question , answer
if on codeigniter 3.x read documentation
on other side, if planning use api internally , scope of project limited can ignore http verbs , make post , calls controllers.
2. creating json response
generally not need use views - can have controllers echo json response. here example of fictional api has api call actor database of actors.
/* ---------------------------------------------- | example of api method actor | database of actors: | call: http://example.com/api/getactorbyid | parameter: actor_id | method: post */ public function getactorbyid(){ // let's first actor id post data $actor_id = $this->input->post('actor_id'); // if api method get // actor id on uri - api call // this: http://example.com/api/getactorbyid/<actor_id> // in case take actor id segment: $actor_id = $this->uri->segment(3); // database query magic here! // ... // ... // let's create array data // in real life comes db query above $data = array( 'firstname' => 'michael', 'lastname' => 'fox', 'isactor' => true, 'userid' => 1234567 ); // let's convert array json $json = json_encode($data); // if api accessed different domain // want allow cross domain access header('access-control-allow-origin: *'); // let's return json echo $json; }
the output this:
{"firstname":"michael","lastname":"fox","isactor":true,"actorid":123456789}
hope helps - luck project!
Comments
Post a Comment