多個點擊我有這樣的AJAX請求對AJAX造成多個PHP執行
function save_details()
{
$('#msgDialog').attr('class', 'alert alert-danger alert-dismissable hide');
$('#msgResult').html('');
BootstrapDialog.show(
{
title: 'Confirmation',
message: 'Save the details?',
buttons: [
{
label: '<i class="fa fa-times"></i> Cancel',
cssClass:'btn btn-danger btn-sm',
action: function(dialogItself)
{
dialogItself.close();
}
},
{
label: '<i class="fa fa-check"></i> OK',
cssClass: 'btn btn-primary btn-sm',
action: function(dialogItself)
{
dialogItself.close(); //i have added this to close the confirmation box so that the user wont click it again
if(xhr_pm && xhr_pm.readyState !=4)
{
xhr_pm.abort();
}
xhr_pm = $.ajax(
{
type :"POST",
url : " {{ Request::root().'/researcher/linkedin_interface/save_details' }} ",
data :
{
id : $('#modalClassifierData').attr('data-record'),
},
success:function(return_data)
{
//additional codes
}
});
}
}]
});
}
而且我有Laravel後端代碼處理插入到數據庫。問題在於,用戶正在進行多次單擊(有意或無意)並導致相同的記錄被插入到數據庫中,因此我現在有多個記錄需要處理。
我正在尋找方法來解決這個後端代碼,而不是使用jQuery來取消Ajax請求,因爲我注意到,即使Ajax請求被取消,它仍然會在服務器中執行。
我已添加驗證以在插入記錄之前檢查狀態,只是點擊之間的間隔太短,因此它未檢測到記錄已添加。
public function saveDetails()
{
$request = \Request::all();
$record = RecordsModel::with('record_details')->get()->first();
//i even tried inserting sleep for 2 seconds but it still does not help, because the interval is just too short.
$check = \LeadsModel::where('id', '=', $record->id)->where('source_id', '=', 1)->get()->count();
if($check > 0)
{
//return already added in the database
}
$rollback_ctr = 0;
DB::beginTransaction();
//save lead
$insert_lead = new LeadsModel();
$insert_lead->name = $record->name;
$insert_lead->country = $record->country;
if(!$insert_lead->save())
{
$rollback_ctr++;
}
else
{
//save lead_details
$insert_lead_detail = new LeadDetailsModel();
$insert_lead_detail->contact_no = $request['no']
if(!$insert_lead_detail->save())
{
$rollback_ctr++;
}
}
if($rollback_ctr > 0)
{
DB::rollback();
//return failed message
}
else
{
DB::commit();
//return successful message
}
}
希望有一個好的建議來解決這個問題。謝謝
更新有時函數需要5秒鐘才能完成執行,所以到那時用戶可以關閉對話框,然後單擊按鈕並再次出現對話框確認。
我選擇了這個,我不同意,jQuery是不是背後的驗證代碼更容易。謝謝。 – Ponce
100%同意,但如果2個用戶點擊您的ajax函數的同一秒,您將以雙記錄結束 –