Why is my toaster notification not working properly in laravel?

Viewed 1627

Using ajax I am updating some value and in response I am showing toaster red (for error) and green (for success) but problem is that if there is error it always shows green toaster. I want a red toaster on error here is my code which I already tried

js

success: function (data) {
    toastr.success(data.message);
},
    error: function(err) {
    toastr.error(err.message);
}

controller

if (some condition){ 
    $customer->save();
    return response()->json([
        'success'=> true
        'message' => 'User status updated successfully.'
    ]);
} else {
    return response()->json([
        'error'=> true,
        'message'=> 'Visit Failed distance is too long'
    ]);
    // this should be red toast but it green
}

Please read comment on above code // this should be red toast but it greencan someone help me how I can show red toaster on error?

1 Answers

success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK.

error: The error function is executed if the server responds with a HTTP error. So if you get an error, then err.message will be undefiend here. So put a custom message instead :

success: function (data) {
     if(data.success == true){
           toastr.success(data.message);
     } else {
           toastr.error(err.message);
     }
},
error: function(err){
     // Your Error Message
     toastr.error("Error with AJAX callback !");
}
Related