简体   繁体   中英

Saving data from jquery

I'm trying to save data from jquery but it doesn't work so I need your help! I'm using CakePHP 2.3. So this is my jQuery

$.ajax({
    url: 'http://localhost/test/reservations/save',
    type: 'POST',
    data: {reservation_time_from : calEvent.start, reservation_time_to: calEvent.end, user_id : "1", laboratory_id : "1"},
    success: function(data) {
        alert("saved")
    }
}); 

Controller

 public function save() {
    if ($this->data != null) {
        $this->Reservation->save($this->request->data);
    }
    $this->autoRender = false;
}

Maybe it doesn't work because of date format in jQuery (Mon Aug 26 2013 11:00:00 GMT+0200)?

Your data is not correctly formatted for passing it to Model::save() . Please refer to the documentation:

http://book.cakephp.org/2.0/en/models/saving-your-data.html

It should be in the following format:

Array
(
    [ModelName] => Array
    (
        [fieldname1] => 'value'
        [fieldname2] => 'value'
    )
)

So the object passed to the AJAX calls data property should look like this:

{ModelName: {fieldname1: 1, fieldname2: 2}}

In your case that would be:

{Reservation: {reservation_time_from: calEvent.start, reservation_time_to: calEvent.end, user_id: 1, laboratory_id: 1}}

Checking for a POST request instead of data being null might also be a good idea, ie:

if($this->request->is('post')) {
    $this->Reservation->save($this->request->data);
}

Also check if you are using the Security Component which may blackhole the request.

And last but not least, check for the date format you've already mentioned, in case validation is involved this might be a problem too, at least it's a problem in case the table column expects a different format. So, format the date properly if necessary, see Convert JS date time to MySQL datetime or http://arshaw.com/fullcalendar/docs/utilities/formatDate/ in case you are using FullCalender (just guessing by your event/property names).

data: {reservation_time_from : calEvent.start, reservation_time_to: calEvent.end, user_id : "1", laboratory_id : "1"},

is not valid json.

You need double quotes on your key to be considered valid.

If reservation_time_from is a variable, then you should create an object literal and add it in the following way:

myDataObject = {};
myDataObject[reservation_time_from] = calEvent.Start;

Once you have built your json object, you can then pass it in as the value for the data key.

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