Ajaxを使ったCakePHPのサンプル : CakePHP

Pocket

フォームの配置順の管理。

フォームの配置順を隠しフィールドid, place使い管理する。
下記例はid, placeをexamplesテーブルで管理する。

フォーム

<form>
    <input type="hidden" name="id" value="1">
    <input type="hidden" name="place" value="1">
</form>
<form>
    <input type="hidden" name="id" value="2">
    <input type="hidden" name="place" value="2">
</form>
<form>
    <input type="hidden" name="id" value="3">
    <input type="hidden" name="place" value="3">
</form>

変更前テーブル

|id|place|..|
|--|-----|--|
|1|1|..|
|2|2|..|
|3|3|..|

何らかの処理で変更されたフォームの並び順をPHPへAjax送信する。

フォーム

<form>
    <input type="hidden" name="id" value="1">
    <input type="hidden" name="place" value="1">
</form>
<form>
    <input type="hidden" name="id" value="3">
    <input type="hidden" name="place" value="2">
</form>
<form>
    <input type="hidden" name="id" value="2">
    <input type="hidden" name="place" value="3">
</form>

JavaScript

jQuery(function ($) {
    // JSON用オブジェクト 
    var o = {};
    $("form").each(function (i, elem) {
        o[i] = {};
        o[i].id = $('input[name="id"]', elem).val();
        o[i].place = $('input[name="place"]', elem).val();
    });
    /* 文字列として取得 */
    var s = JSON.stringify(o);
    /* クエリ文字列作成(key=value) */
    var data = "order=" + s;
    $.ajax({
        url: '/examples/move',
        type: 'POST',
        success: function(response) {...},
        error: function(response) {...},
        data: data,
        dataType: 'json'
    });
});

CakePHP側

public function move() {
    if ( $this->request->is( 'ajax' ) ) {
        // クエリ文字列を配列へ変換
        $order = json_decode( $this->request->data['order'], true );
        $data = [ 'Example' ];
        for ( $i = 0; $i < count($order); $i++) {
            $data['Example']['id'] = $order[ $i ]['id'];
            $data['Example']['place'] = $order[ $i ][ 'place' ];
            // Exampleテーブル更新
            $this->Example->save($data) ) {
        }
        $response = {
            message = '処理完了';
        }
        header( "Content-Type: application/json; charset=utf-8" );
        echo json_encode( $response );
        exit;
    }
}

変更後テーブル

|id|place|..|
|--|-----|--|
|1|1|..|
|2|3|..|
|3|2|..|

コメント

No comments yet.

コメントの投稿

改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。