実現したいこと
Laravel5.5にてvue.js, axiosを利用し非同期でデータをDBに挿入。
現状
学校のシステムを作成。
画像は先生が空きのある時間をclick→DBに「日付」「時間」のデータ(例 1,2)を挿入したい
問題点
ajaxでサーバ側にデータを渡すのがうまくいっていない。詳細はコード内に記載しておきました。
「html部分」
<tr v-for="(row,rowIndex) in rows"> <th scope="row">@{{ row.time }}</th> <td scope="row" class="hoge" v-for='(col,colIndex) in row.columns' v-bind:class='{ active: col.isActive }' v-on:click='empty(rowIndex,colIndex)'>@{{ col.date }}:@{{ row.number }}</td> </tr>
「js,method部分」
methods:{ empty:function(rowIndex,colIndex){ this.rows[rowIndex].columns[colIndex].isActive = ! this.rows[rowIndex].columns[colIndex].isActive; this.$http.post('/ajax/path', rowIndex, colIndex)//ここの引数の渡し方が不明です。html側で使用したrowIndex・colIndexの値がサーバ側に送れればokです .then(function(response){ alert("成功!!!");//テストのため }).catch(function(error){ alert('送信が失敗しました。');//テストのため }); } }
「サーバ側」
public function store(rowIndex, colIndex) //←このようにデータをわたすことはできないのか?? { $time_id = 1; //ここにrowIndexの値を入れたい $date_id = 2; ///ここにcolIndexの値を入れたい(0だとその日の日付、1だと翌日の日付をDBにいれたいので変更しなければいけませんが) $teacher_id = 1; $user_id = 1; $reservation_calender = new Reservation_calender(); $reservation_calender->time_id = $time_id; $reservation_calender->teacher_id = $teacher_id; $reservation_calender->user_id = $user_id; $reservation_calender->save(); return response()->json([ 'result' => true ]); }
よろしくお願いいたします。
質問を受けての追記
mts10806さん、質問ありがとうございます。
参考にしたurl
https://blog.capilano-fw.com/?p=261(laravel,axios使用での一通りの流れを参考にした)
https://www.yoheim.net/blog.php?q=20170801(axiosの詳細はこちらで)
試してみたこと
上のサイトを参考にして、js側に引数に情報をいれた(こちらはこれで間違っていないと思われる)
methods:{ empty:function(rowIndex,colIndex){ this.rows[rowIndex].columns[colIndex].isActive = ! this.rows[rowIndex].columns[colIndex].isActive; const data = { rowIndex : rowIndex, colIndex : colIndex }; //console.logで値が取れていることは確認済 console.log(data.colIndex); console.log(data.rowIndex); this.$http.post('/ajax/reservation_calender/from_teacher', data) .then(function(response){ // 成功したとき alert("成功!!!");//テストのため }).catch(function(error){ // 失敗したとき alert('送信が失敗しました。');//テストのため }); } }
server側にてとりあえず、引数関係なし+数値をそのまま入れてDBに挿入
→DBに値は入った
public function store() { $time_id = 1; $date_id = 1; $teacher_id = 1; $user_id = 1; $reservation_calender = new Reservation_calender(); $reservation_calender->time_id = $time_id; $reservation_calender->teacher_id = $teacher_id; $reservation_calender->user_id = $user_id; $reservation_calender->save(); return response()->json([ 'result' => true ]); }
他のcontrollerの書き方を真似て引数を受け取り、DBに入れようとする
→ajax送信失敗
public function store(data $data) { $time_id = $data[rowIndex]; $date_id = $data[colIndex]; $teacher_id = 1; $user_id = 1; $reservation_calender = new Reservation_calender(); $reservation_calender->time_id = $time_id; $reservation_calender->teacher_id = $teacher_id; $reservation_calender->user_id = $user_id; $reservation_calender->save(); return response()->json([ 'result' => true ]); }
回答1件
あなたの回答
tips
プレビュー