Saving data from jquery

大兔子大兔子 提交于 2019-12-25 11:01:08

问题


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)?


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/18422675/saving-data-from-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!