LoginSignup
25
14

More than 3 years have passed since last update.

Laravel+jQueryでAjax通信してみる

Last updated at Posted at 2020-12-03

自分の中でなんと無くとっつきにくさを感じてたjQueryですが、コントローラーとJS間の値の受け渡しについて自分なりにまとめてみました。

Ajaxの基本の書き方


$(function(){
  $.ajax({
    type: "get", //HTTP通信の種類
    url:'/home', //通信したいURL
    dataType: 'json'
  })
  //通信が成功したとき
  .done((res)=>{
    console.log(res.message)
  })
  //通信が失敗したとき
  .fail((error)=>{
    console.log(error.statusText)
  })
});

$(function)で、画面が読み込まれたタイミングで発火させることができる(vueでいうmounted的なやつ??)

関数の書き方


$('セレクタ').イベント名(function(){
  //イベント発生時に実行したい処理
});

【GETメソッド】 DBの値を取得してHTMLに表示する

//ボタンを押したタイミングで発火する
$("#bt").click(function () {
  $.ajax({
    type: "get", //HTTP通信の種類
    url: "/getuser",
    dataType: "json",
  })
    //通信が成功したとき
    .done((res) => { // resの部分にコントローラーから返ってきた値 $users が入る
      $.each(res, function (index, value) {
        html = `
                      <tr class="user-list">
                          <td class="col-xs-2">ユーザー名:${value.name}</td>
                      </tr>
         `;
      $(".user-table").append(html); //できあがったテンプレートを user-tableクラスの中に追加
      });
    })
    //通信が失敗したとき
    .fail((error) => {
      console.log(error.statusText);
    });
});
  • $("#要素名")で、idを指定することができる。
  • $(".要素名")で、classを指定することができる。

サーバー側の処理で、users テーブルの値を全て取ってきて、$usersに代入してjsonとして返す。

   public function getUser()
  {
    $users = User::select('name','email')->get();
    return $users;
  }

【POSTメソッド】

$("#bt2").click(function () {
  $.ajaxSetup({
  headers: {
    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
  },
});
  $.ajax({
    //POST通信
    type: "post",
    //ここでデータの送信先URLを指定します。
    url: "/postgmail",
    dataType: "json",
    data: {
      uid: 100,
      subject: "テストタイトル",
      from: "テストfrom",
      body: "テストbody",
    },

  })
    //通信が成功したとき
    .then((res) => {
      console.log(res);
    })
    //通信が失敗したとき
    .fail((error) => {
      console.log(error.statusText);
    });
});
// コントローラー側
 public function postGmail(Request $request)
  {
    $result = $request->all();
    return $result;
  }
// ルーティング
Route::post('/postgmail', 'HomeController@postGmail');

console.log(res)で値が確認できました。
image.png

AjaxでPOSTした値をDBに保存する

AjaxでPOSTした値をDBに保存します。
上記のAjaxの記述はそのままで、コントローラー側を編集します。

// 一番上の useの部分に追記
use App\Gmail;
=== 省略 ===
  public function postGmail(Request $request)
  {
    $gmail = new Gmail();
    $gmail->uid = $request->uid;
    $gmail->subject = $request->subject;
    $gmail->from = $request->from;
    $gmail->body = $request->body;

    $gmail->save();
  }

値が保存されました。
image.png

25
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
14