[英]How to update database with AJAX & Laravel 5.2?
我想使用AJAX和Laravel 5.2框架更新數據庫表列。 我有一個Delier
按鈕,當我單擊該按鈕時,它將把“ Not Shipped
列更新為“已Shipped
。 我還使用sweetAlert插件進行彈出樣式設置。 我搜了很多。 但是我沒有找到完美的程序。 我已經嘗試過這種方式:
路線:
Route::get('/winner/status/{id}', ['as' => 'winner.status', 'uses' => 'WinnerController@statusUpdate']);
WinnerController:
public function statusUpdate(Request $request, $id)
{
$winner = Winner::find($id);
$winner->product_stat = "Shipped";
$winner->save();
$request->session()->flash('alert-info', 'Product Status Updated!');
return Redirect::to('admin/winner/detail');
}
視圖中的腳本:
$(".action-button").click(function(){
swal({
type : 'warning',
title: 'Submit what you want',
input: 'text',
showCancelButton: false,
confirmButtonText: 'Submit',
showLoaderOnConfirm: true,
allowOutsideClick: false
}).then(function (text) {
$.ajax({
type: "POST",
url : '',
success: function(data){
swal('Confirmed!','success')
}
});
})
});
刀:
@foreach($dataQrDetails as $dataQr)
<tr>
<td> {{ $dataQr->product_name }} </td>
<td> {{ $dataQr->product_stat }} </td>
<td> {{ $dataQr->created_at }} </td>
<td> <a class="btn btn-info btn-xs action-button" href="{{route('winner.status',$dataQr->id)}}">Delier</a></td>
</tr>
@endforeach
刀片前端:
這是正在更新的列,但更新后重定向了另一個頁面,並且顯示的只是彈出窗口,因此無需提交彈出窗口確認按鈕。 反正有這樣做嗎? 請任何人回答我下面的問題:
- 與Laravel一起使用AJAX的最佳過程是什么?
- 什么是更新數據的路由調用?
- 如何定義AJAX網址?
許多JavaScript框架還使用“大括號”來指示應在瀏覽器中顯示給定的表達式
在laravel中的ajax請求中傳遞變量的最佳方法]
你的路線是
Route::get('testUrl/{id}', 'TestController@getAjax');
ajax請求
<script>
var Id = <?php echo $id; ?>
$(function(){
$('#button').click(function() {
$.ajax({
url: 'testUrl/{id}',
type: 'GET',
data: { id: Id },
success: function(response)
{
$('#something').html(response);
}
});
});
});
</script>
TestController.php
public function getAjax()
{
$id = $_GET['id'];
return $id // any value return as a response
}
此處的操作是,當您加載表單時,我會將用戶ID保存在“隱藏”字段中,當我提交時,它也會將其傳遞給控制器
通知
<input type="hidden" name="id" value="{{ $id }}">
在AJAX中
$.ajax({
url: "/update-winner",
type:'POST',
data: {_token:_token, id:id, .....},
success: function(data) {
if($.isEmptyObject(data.error)){
swal('Confirmed!',data.success); # or swal('Confirmed!','success')
}else{
swal('error!',data.error); # or swal('error!','Errorrrrr')
}
}
});
途中
Route::post('update-winner','HomeController@statusUpdate');
在控制器中
function statusUpdate()
{
<!-- if need -->
$validator = Validator::make($request->all(), [
/....
]);
if ($validate->fails())
{
return response()->json(['error'=>$validator->errors()->all()]);
}
else
{
$id = $request->input("id");
$winner = Winner::find($id);
$winner->product_stat = "Shipped";
$winner->save();
return response()->json(['success'=>'Added new records.']);
}
}
編輯01
在刪除按鈕中,添加此data-delete="{{ id_fiedld_name}"
在阿賈克斯,你可以抓住
var id = ($(this).data('delete'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.