Jquery how can I deal with no data response from api call?

84 views Asked by At

I am using jquery and ruby to search phone numbers with the Plivo api. Sometimes I get back no data, the console log says []. In such cases I would like to be able to print a message which says "No data returned ..." or some such kind message.

The jquery is:

$(document).ready(function() {
    $("#searchnumbers").click(function() {
    var country_iso = $("#countrynumbers").val();
    var region = $("#region").val();
    var prefix = $("#prefix").val();
    $.getJSON("/searchnumbers?country_iso="+country_iso+"&region="+region+"&prefix="+prefix, function(data) {
       if( data.length == 0 ) {
        $(".results").html("no Records");
              } else {
            $.each( data, function( key, value ) {
               $(".results").append('<p>' + this["region"] + '</p>');
               }); 
             } 
         }); 
      }); 
 }); 

When the response returns data then I have no problem but when the search is invalid (Moscow in Australia, for example) then the console log says [ ] but my if clause, above, does not work and nothing is printed in the $(".results") div.

How can I do this to be able to give an error message of no data is returned? Thanks!

0

There are 0 answers