もがき系プログラマの日常

もがき系エンジニアの勉強したこと、日常のこと、気になっている技術、備忘録などを紹介するブログです。

cakephp3でajax(post)通信

こんばんは。小ネタというか、今さっき覚えたことです。

js側

var save_data = {
   ....
   ...
   ..
   .
};

$.post({
    url:      '/test/ajaxSave',
    dataType: 'json',
    data:     save_data
}).done(function(response) {
    if (response.result === 'NG') {
        alert('保存失敗');
        return false;
    }
    
    alert('保存成功');
    return true;
}).fail(function() {
    alert('通信失敗');
});

php(Controller)側

<?php

class TestController extends AppController
{
    public function ajaxSave()
   {
        if (!$this->getRequest()->isAll(['ajax', 'post'])) {
            return $this->getResponse()->withType('json')->withStringBody(json_encode([
                'result' => 'NG'
            ]));
        }

        // 何かの保存処理

        return $this->getResponse()->withType('json')->withStringBody(json_encode([
            'result' => 'OK',
        ]));
    }
}

これで通信可能。

ajax通信かつ、postの通信かどうかをisでどう判断するのかとコアを見てたら、isの第一引数は配列OKだったけど、

<?php

        if (is_array($type)) {
            $result = array_map([$this, 'is'], $type);

            return count(array_filter($result)) > 0;
        }

という感じでどれか一つだけでもtrueであればOKになっちゃうので使えなかった。

他を探すと isAll() というドンピシャのやつがあったので、これを使用しました。

<?php

    public function isAll(array $types)
    {
        $result = array_filter(array_map([$this, 'is'], $types));

        return count($result) === count($types);
    }

is() の第一引数配列で渡されたら、 isAll() を走らせればいいのに・・・