How to check if REST Service results are empty, the proper way.
To check if the response from a REST service request is empty you need to use two different methods. You can not be sure that a call to (data.length == 0) will not fail. The most valid way to check the response is to also check if it is null.
In it's simplest form, you would want to do the following:
span
if(data == null || data.length < 1){
// run your function
}
/span
However not all services will produce an empty response in the data array when no records are found. You will need to make sure that the array you are checking actually returns empty in the event there are no records returned. Below is an example of a response from Google that returned no records.
Google Places API call example:
span
{
Code: Select all
"html_attributions" : [
],
"results" : [
],
"status" : "ZERO_RESULTS" }
/span
As you can see there is data being returned in the data array but the results array is empty, which in this case the (data.length) or (data == null) both would return false because the data array is not empty.
You would need to change your code to the following:
span
if(data.results == null || data.results.length < 1){
// run your function
}
/span
With the Google Places response example above you could also do it this way:
span
if(data.status == 'ZERO_RESULTS'){
// run your function
}
/span
I hope this helps. Feel free to ask me questions, I enjoy helping where I can.