laravel5.1で、jqueryとajaxを使って、リアルタイムにMySQLを更新する方法。
管理画面などマスタ系(商品のカテゴリーマスタとか、分類マスタとか)は、個別の編集画面に遷移せずに一覧で更新・削除がしたい事が多いので、作ってみました。
表示順序や優先順位なども指定したかったので、jqueryのsortableを使ってみた、簡単!
作ってみた感想(ハマった所)
1, ajaxでGET以外(POST/PUT/DELETE)の操作をする場合には、CSRFトークン(外部から操作されないための通行証)が必要!
2, DELETEする時は、PUTみたいにURL指定が「対象クラス名/レコード番号」でないとダメ!
3, リロードせずにjQueryだけのDOM操作だと、直感的でUI的に優れているな~。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script> <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script> {{-- csrfトークンを忘れると、レコード操作が出来ない! --}} <meta name="csrf-token" content="{{ csrf_token() }}"> <script>   // GET以外では、csrfトークンが無いとエラーになる。   $.ajaxSetup({         headers: {             'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')         }   });       $(function() {     // jquery-uiを使って、表をD&Dで並び替え可能にする     // sortableは直下の要素を「並び替え可能」にする!     $('#sortable-table1').sortable({                 // 並び替えされたら、MySQLに反映させる。         update : function(ev, ui)         {             // 変更後の順番配列を取得             arr_rec = $(this).sortable("toArray");             // 全てのレコードに対して、表示順を更新する。             for (var i = 0, len = arr_rec.length; i < len; i++) {                 console.log(arr_rec[i]);                 $.ajax({                    type:'PUT',                    url:'product_class/' + arr_rec[i],                    data: {'orderby_id': i+1},                    success:function(data){                       console.log(data);                    }                 });                                    }             // 表示順のセルに、番号を振り直す             var i = 1;             $(".class_orderby_id").each( function() {                 $(this).text(i++);             });                     }     });     // テキストボックスからフォーカスが離れたら、入力されている文字列でレコード更新する     $(".textbox").focusout(function(){         // フォーカスの外れたレコードIDと文字列を取得         var record_id = $(this).parent("td").parent("tr").attr('id');         var record_text = $(this).val();         // MySQLレコードを更新         $.ajax({            type:'PUT',            url:'product_class/' + record_id,            data: {'class_name': record_text},            success:function(data){               console.log(data);            }         });          });     // 削除ボタンを押されたら、確認ダイアログを出して、OKならレコード削除する     $(".delete_button").on('click', function(){         if(confirm("削除しますか?") === false){             return false;         }         // 削除する行のレコードIDを取得         var record_id = $(this).parent("td").parent("tr").attr('id');         $.ajax({            type:'DELETE',            url:'product_class/' + record_id,            data: {},             success:function(data){                 // 削除ボタンの押された行を、画面から削除する                 $('#' + record_id).remove();                 // レコードのorderby_idは歯抜けになるが、表示順的には問題ない。                 // 表示順のセルに、番号を振る                 var i = 1;                 $(".class_orderby_id").each( function() {                     $(this).text(i++);                 });                             },            // リレーション制約で削除できない場合は、エラーを返す            error:function(data){               return alert('商品で使用されているため削除できません!');            }         });          });       }); </script> <table border='1' >        <thead>     <tr>                 <th>表示順</th>         <th>分類名</th>         <th>削除</th>     </tr>     </thead>     <tbody id="sortable-table1">       <?php $i = 1; //表示順用のカウンタ ?>       @foreach($all_classes as $class)           <tr id="{{ $class->id }}">                         <td class="class_orderby_id"> {{ $i++ }}</td>                                <td><input type='text' value='{{ $class->class_name }}' class='textbox'> </td>                        <td><input type='button' value='削除' class='delete_button'> </td>           </tr>       @endforeach     </tbody>    </table> | 
