ajaxとcakephp3
自分用のただのメモ。
cakephp: 3.x (2016/04/2? 時点での最新版だったかな)
php: 7.0.0
jQuery: 2.2.6 (だったかな)
ここからcode
$(function() {
    $('#ajaxbutton').click (function () {
        $(this).text("押された");
        alert("押された");
        $.ajax({
            url: "http://localhost:8888/appname/controller/action",
            type: "post",
            dataType: "html"
        }).done(function (response) {
            $("#tag").html(response);
            alert("success");
        }).fail(function () {
            alert("failed");
        });
    });
});
これは、$('#ajaxbutton').click...
はajaxbuttonっていうIDがついてるボタンがクリックされたらっていう処理です。
ボタンがクリックされると初めに$(this).text("押された")でajaxbuttonIDがついてるところのテキストを”押された”に変えました。次に、alertで別windowでアラートします。それから、非同期通信をajaxで行います。
urlは実行する先です。cakephpで行っているので、実行したいコントローラーの関数のurlにします。
type:はpostとgetが選べますが、自分はよくわかりません。
datatype: はよくわからんけど、とりあえずこうしてるとうまくいってる。
done()は、urlから読み込みが成功すると実行され、failは失敗すると実行されます。
$("#tag").html(response)はtagっていうIDをもっているところにresponseを埋め込みます。
responseはきっと、phpの実行結果。phpの実行結果はhtmlでかえってくるから。。
<button id="ajaxbutton">ボタン</button>
<div id="tag">
  <!-- ここにAjaxで実行したphpの結果が書き込まれる。 -->
</div>
あと、cakephpでの注意点
$this->autoLayerやら、$this->autoRenderなんかでよくわからん。
だからとりあえず、こうしとけばおけ。
<?php
namespace App\Controller;
use App\Controller\AppController;
class TestController extends AppController {
    public function index () {
        $this->viewBuilder()->layout("");
        $this->render("index");
    }
    public function test () {
        $this->autoRender = false;
        if ($this->request->is("ajax")) {
            echo "ajax";
        } else {
            echo "not ajax";
        }
    }
}
?>
viewBuilderは読み込むLayerのctpを決めます。
render("index")はTemplate/Test/index.ctpを読み込みます。
これで、indexを実行すると、index.ctpに書かれてるhtmlファイルで出力します。
autoRenderをfalseにすると、その関数内で書いたやつのみhtmlで出力します。
テンプレはいらないってことです。このtestですと、echoだけ表示されます。
is("ajax")はajaxで呼ばれた時、trueを返します。
これで、ajaxのときとそうでないときでわけれます。
cssのメモ
なんかbootstrap使いやすい。けど、ナビゲーションバーがちょっと。。。って感じがする。
materialUIっていうのもいいかもしれない。
しぬほど関係ないけど、jsで関数のプロットができた。。
どっかから拾ってきた、、、
g("block")をはずすと、ズームとか移動とかできる。
    <div>
        <iframe src="http://graph.tk/" id="my_graph" style="width:500px;height:400px">
</iframe>
<script>
var my_graph=document.getElementById("my_graph");
my_graph.onload=function(){
    function g(m){
        my_graph.contentWindow.postMessage(m,"http://graph.tk");
    };
    g("add:x^3+1");
    g("add:e^x");
    g("block");
    g("center:1,2");
    g("scale:2");
}
</script>
//Methods include: add, block, empty, scale, translate, center
    </div>
どうでもいいけど、jqueryわからないから、いろいろと調べてるんだけど、どれも関数のなかに関数書いててネストがめちゃくちゃきもちわるいことになってる。