Ajax 更新字段数据库字段在 laravel 刀片模板中



我有一个酒店列表,如果它更新了我想在主页上提醒它的字段,我想更新所选酒店的数据库。 这是 AJAX 函数

function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'{{ route('home', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
success:function(data){
alert(data);
},
error: function (result) {
alert("Error occur in the update()");
}
});

}

} 我的控制器

public function update(Request $request, $hotel_plan_id)
{ 
$hotel=plan_hotel::where('hotel_plan_id', $hotel_plan_id)->first();
$hotel->hotel_name = $request->input('hotel_name');
//$hotel ->room_name = $request->input('room_name');
$hotel->save();
// return redirect('/home')->with('success', 'price updated');
}

我的路线

Route::post('home/{hotel_plan_id}', 'HomeController@update')->name('home');

我的选择表单

{!! Form::select('hotel_name', array($item[4], $item[10]),'S', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onclick'=>"showRoom(this.value, $item[8])"));!!}

您使用 ajax url 时遇到错误,并且您没有传递酒店名称的值。

检查此更改。

function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'/home/' + id,
data:{_token:'{{ csrf_token() }}', hotel_name: 'Your value here'},
});
}

请返回 json 响应

return response()->json();

你必须像这样返回 json 对象

return response->json([
'status'    =>  200,
'result'    => true,
'error'     => false,
'data'      => $hotel
]);

最新更新