简体   繁体   中英

Passing HTTP Request from Backbone.js to CodeIgniter to DB

I am trying to sync up model in Backbone.js to Codeigniter using a RESTful api written by Philip Sturgeon @ http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/ I am trying to add an entry to the user resource group. The problem is: I will get a new entry, but title would be 0 instead of "Hello World,,." I believe the breakdown is at 'title'=>$this->post('title') in the controller? because when I replaced it with 'title'=>"FOO", Foo will show up in the DB. Any thoughts? Btw, should I put as the URL in backbone.js

url: "MyApp/index.php/app/user"    or
url: "MyApp/index.php/app/user/id/(xxx)"

Backbone.js

$(document).ready(function(){
var Item = Backbone.Model.extend({

defaults: {
  title: "Hello World!!!"
},

url: "MyApp/index.php/app/user"

});
var item=new Item;  
item.save();

app.php (Controller)

function user_post()
{
    $data=array(
    'id'=> NULL,
    'title'=>$this->post('title')
    );

    $result = $this->App_Model->create($data);
}

app_model.php (Model)

function create($data)
{

    $query = $this->db->insert('data', $data)
}

UPDATE::

This is from the Chrome Inspector

Request Method:POST

Status Code:200 OK

Request Headersview source

Accept:application/json, text/javascript, / ; q=0.01

Connection:keep-alive

Content-Length:15

Content-Type:application/json

X-Requested-With:XMLHttpRequest

Request Payload {“title”:“my Content!!”}

I had some problems with this as well. My solution:

$data = json_decode(file_get_contents('php://input'), true);
$this->site_model->create($data);

You need to change this line under your Controller:

$this->post('title')

To

$this->input->post('title')

or actually you can use plain PHP for accessing your POST global variables, like $_POST['title'].

As reference, check the CodeIgniter's Input Class

I'm not too sure as to why your title param is not getting passed. I would recommend using Firebug or Chrome Inspector to check if the title param actually got sent. You can narrow down your debugging from there.

As for the URL, the RESTful way to do it would be to use MyApp/index.php/app/user/id" to manage a single user

EDIT

It looks like your request is sent fine. I would examine the post data. Why not print the post data and see what is received. My guess is PHP is not reading the JSON data correctly. You can use $decoded = json_decode($this->post('title')) to turn it into a php object.

What about using $this->input->post('title'); ? ( Reference )

Try accessing

$this->request->body

It should contain the contents of all the values you are posting via Backbone.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM