Maurice Kroon
Maurice Kroon

Reputation: 959

AJAX failure after using jQuery sortable in CakePHP

I used to use scriptaculous in all my CakePHP projects because of its easy helpers. In time, I got more and more into jQuery, and now I want to replace my current scriptaculous scripts with jQuery scripts. Until now, everything has been good... except jQuery sortable.

JQuery sortable runs, but the AJAX call afterwards isn't working right. Now my programmer is on holiday so I've gotta ask you guys:

Old CakePHP code (inside pages_controller.php):

function order($parent_id = 0){
    $this->autoRender=false;

    //Users with rights may view this
    $user = $this->checkRights('pages',true);

    //loop through the data sent via the ajax call
    foreach ($this->params['form']['page'] as $order => $id){
        $this->Page->id = $id;
        if(!$this->Page->saveField('order',$order)) {
            $this->flash('Really freaky errors are occuring','/');
            exit();
        }
    }

}

My jQuery looks like:

    $(".sortable-list").sortable({
    update: function() {
        $.post('/pages/order/0', {
            data: $('.sortable-list').sortable("serialize")
        });
    }
});
$(".sortable-list").disableSelection(); 

With Firebug, I see that the AJAX post call produces something like this:

    page[]=14&page[]=23&page[]=18&page[]=11&page[]=26&page[]=28

However, it doesn't seem to work. I guess the page[]=id is different that the old scriptaculous format:

pages_0[] 1
pages_0[] 3
pages_0[] 2

Does anyone know how I can adjust the CakePHP file to read the string correctly?

Upvotes: 0

Views: 2543

Answers (3)

Maurice Kroon
Maurice Kroon

Reputation: 959

Ah, finally.. It turned out that jquery's output was: data: '&page_0[]=1etc'. I had to make it page_0 instead of data and its fixed!

So:

    $(".sortable-list").sortable({
    update: function() {
        $.post('/pages/order/0/, $('#pages_0').sortable("serialize", {key: 'pages_0[]'}))
    }
});
$(".sortable-list").disableSelection(); 

I removed the {} from the second argument of $.post and it turned out to be the winner! thx for the help guys!

Upvotes: 0

Sergei
Sergei

Reputation: 2757

before foreach line, insert

debug($this->params['form']['page']);

and see how page array looks like. then iterate properly.

Upvotes: 0

Artem Barger
Artem Barger

Reputation: 41232

I don't have working php environment to test, but should work basically.

$pages = $_GET['page'];

foreach( $pages as $order => $id)
{
     $this->Page->id = $id;
            if(!$this->Page->saveField('order',$order)) {
                        $this->flash('Really freaky errors are occuring','/');
                        exit();
                }

}

PS. Probably you have kind of problem updating "$this->params".

Upvotes: 1

Related Questions