My ajax code always receives a success response even in case of error. I'm using Laravel 8.2.
Here is JavaScript
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
if(confirm('Do you want to delete?')){
$.ajax(
{
url: "operDel/" id,
type: 'post',
cache: false,
data: {
"id": id,
"method": 'post',
"_token": token,
},
dataType: "json",
success: function() {
alert('Record is deleted'); // I getting only this alert
},
error: function() {
alert('You can not delete this record');
}
});
}
});
Here is Route
Route::post('operDel/{id}', '\App\Http\Controllers\OperationController@destroy')->name('operDel')->middleware('auth');
Here is Contoller
public function destroy($id)
{
$user = User::find($id);
if($user->type !== 0) {
$user->delete();
return response()->json([
'success'=>"Record deleted."
]);
}
else{
return response()->json([
'error' => "You can not delete this"
]);
}
}
The controller is running without error, it deleted record from DB when $user-> type! == 0. But I'm getting only the alert within the success function. How can I display response message to alert?
CodePudding user response:
You need to send error response codes in order for AJAX to consider a response to have failed, for example:
public function destroy($id)
{
$user = User::find($id);
if($user->type !== 0) {
$user->delete();
return response()->json([
'success'=>"Record deleted."
]);
}
else{
return response()->json([
'error' => "You can not delete this"
], 400); // 400 means bad request
}
}
Sending a response code that's 400 will make AJAX understand that there was an error.
CodePudding user response:
public function destroy($id)
{
$user = User::find($id);
if($user->type !== 0) {
$user->delete();
return response()->json([
'status' => 'success', "message" => "Record deleted."
]);
}
else{
return response()->json([
'status' => 'error', "message" => "You can not delete this"
]);
}
}
Edit your controller like this.
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
if(confirm('Do you want to delete?')){
$.ajax(
{
url: "operDel/" id,
type: 'post',
cache: false,
data: {
"id": id,
"method": 'post',
"_token": token,
},
dataType: "json",
success: function(response) {
if(response.status == "success"){
alert('Record is deleted'); // I getting only this alert
}else if(response.status == "error"){
alert('You can not delete this record');
}
},
});
}
});
This is one way to use it like that. You function always return success. Bacause you did not use your controller try catch and there is no error. if error occured your js will work.