I’m currently stuck on an issue where I’m unable to handle 404
or 500
error with jQuery AJAX. I’m fetching some data from controller, and I’m returning json()
with relevant status code:
public function getFilteredProducts(Request $request){
$products = Product::where('product_category_id', $request->category_id)->get();
if(count($products)){
return response()->json([
'products' => $products,
'category_id' => $request->category_id,
], 200);
}else{
return response()->json([
'product_category_id' => $request->category_id
], 404);
}
}
This is my AJAX function:
$.ajax({
url: `/shop/filtered-products/${category_id}`,
type: 'get',
headers: {
'X-CSRF-TOKEN': window.csrfToken
},
success: function (data) {
//Do something on succes
},
statusCode: {
404: function (data) {
//Hande 404 code
},
500: function (data) {
//Handle 505 code
}
}
});
This works perfectly when there are products found & when I return 200
status. But the problem occurs when I return 404
status code & statusCode
functions are not getting called. I can see the error in console, but the code is not executing:
I also tried to handle errors with error
function, but no luck either:
$.ajax({
url: `/shop/filtered-products/${category_id}`,
type: 'get',
headers: {
'X-CSRF-TOKEN': window.csrfToken
},
success: function (data) {
//Do something on succes
},
error: function (data) {
//Handle any errors
},
});
Expected result would be to execute some code on any of the following status codes(404
or 500
). What am I doing wrong here? Thanks in advance.
3
Answers
I managed to resolve this by using different parameters in AJAX error function, something like this:
When I added LHttpRequest, textStatus, errorThrown parameters, my error was getting caught in AJAX as expected. To return errors, I used this in controllers to return exceptions:
In your controller just thrown an exception, which you can handle in the render function.
Don’t forget to use this class above:
In "app/Exceptions/Handler.php" add the code-block before existing line (by default).
That’s it. But remember, this is just one of many solutions. Actually you can create your custom exceptions and thrown them. For more you can see here
Try to add this:
Handled for you by Laravel expectsJson() in render() method