【发布时间】:2021-08-16 06:30:25
【问题描述】:
我正在将数据从 MySql 查询发送到 Blade.php。我正在将这些数据传递给一个表。
然后我有一个 php foreach 循环,它遍历查询中的每一行。
我正在尝试使用 ajax 更新 td 中的各个行,但无论您更新哪一行,它总是采用最后一行的值并将所有行更新为相同的值。
它也没有将正确的 id 传递给 ajax 请求。它传递第一行 id,但使用最后一行数据进行更新。
您能帮我找出我的问题吗?
这里的想法是能够更新各个行。因此,我想通过我的 ajax 请求将带有 name="phone_id" 的隐藏输入中的值传递给我的 php 函数。目前它只传递隐藏输入字段的第一行值。
首先是表格
<div class="row">
<div class="col-12 col-md-8 offset-md-2 text-center mt-30 rename">
<table class="table">
<thead>
<tr>
<th scope="col">Number</th>
<th scope="col">Description</th>
<th scope="col">Balance</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
@foreach ($phones as $phone)
<tr>
<th scope="row"><input value="{{$phone->phone_account}}" type="text" name="phone_account{{$phone->phone_id}}"></th>
<td><input value="{{$phone->description}}" type="text" name="description{{$phone->phone_id}}"></td>
<td><input value="{{ $phone->balance }}" disabled></td>
<td>
<input type="text" value="{{ $phone->phone_id }}" name="phone_id" hidden>
<input id="VerifyBtn" onclick="postData()" type="submit" class="btn btn-profile" value="Update">
<a href="{{ route('phonedelete', ['id'=>$phone->phone_id]) }}" role="button" class="btn btn-profile">Delete</a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
Ajax 请求
function postData() {
var id = $("input[name=phone_id]").val();
var phone_account = $("input[name=phone_account{{$phone->phone_id}}]").val();
var description = $("input[name=description{{$phone->phone_id}}]").val();
var user_id = {{$phone->user_id}};
$.ajax({
url: '{{ route('update_phone.post')}}',
type: 'POST',
data: {
phone_account: phone_account,
description: description,
user_id: user_id,
id:id,
},
cache: false,
success: function (data) {
var data = data;
console.log(data)
if (data == 'success') {
$('#success').show();
$('#success').html('phone account successfully updated.');
}else{
alert('Error occurred, please try again later...');
}
}
});
}
更新功能
public function update_phone(Request $request){
$id = $request->id;
$user_id = $request->user_id;
$phone_acc = $request->phone_account;
$phone_desc = $request->description;
$date = date("Y-m-d H:i:s");
DB::table('phone_details')
->where('user_id', $user_id)
->where('phone_id', $id)
->update(['phone_account' => $phone_acc,
'description' => $phone_desc,
'updated_at' => $date]);
echo 'success';
}
【问题讨论】:
-
将 id 分配给 tr 并在 ajax 中使用。
标签: php jquery ajax laravel foreach