I am working on a project where my website interacts with an API hosted on a different server. The website makes API calls and displays the data in a table. However, I want to implement a way to alert the user client-side using JavaScript if the API server is unreachable. What would be the most effective approach for handling this situation?
Should I include the alert message within the error handling of the API call (refer to the code snippet below)? I'm seeking advice on the best practices for addressing this issue.
function apiCall(query, product) {
var p = product;
var urlr = 'https://myFakeAPIUrl/api/' + query + '/' + product;
$.ajax({
contentType: 'application/json',
crossDomain: true,
url: urlr,
type: "GET",
success: function(result) {
alert("Yay, the API server is up.");
},
error: function(error) {
console.log(error);
alert("Sorry, the server is down.");
}
});
}
var productData = apiCall("Produce", "112233");