jQuery(function ($) {
        // OnKeyDown Function
        jQuery("#billing_postcode").keyup(function () {
            var zip_in = jQuery(this);
            var zip_box = jQuery('#billing_postcode');
            var cou = jQuery('#billing_country').val();
            if (zip_in.val().length < 4) { zip_box.removeClass('error success'); } else if (zip_in.val().length > 8)
            {
                zip_box.addClass('error').removeClass('success');
            } else if (cou == 'GB') {
                //alert('hi');
                jQuery.ajax({
                    url: "http://api.postcodes.io/postcodes/" + zip_in.val(),
                    cache: false,
                    dataType: "json",
                    type: "GET",
                    success: function (results, success) {
                        // Make the city and state boxes visible
                        //var obj = JSON.stringify(results);
                        //alert(results.result.country);
                        jQuery("#billing_city").val(results.result.region);
                        jQuery("#billing_state").replaceWith('<input class="form-control" type="text" name="billing_state" id="txtCity" />');
                        jQuery("#txtCity").val(results.result.country);
                        zip_box.addClass('success').removeClass('error');
                    },
                    error: function (results, success) {
                        zip_box.removeClass('success').addClass('error');
                    }
                });
            }
            else if ((zip_in.val().length == 4) || (zip_in.val().length == 5))
            {
                // Make HTTP Request
                jQuery.ajax({
                    url: "http://api.zippopotam.us/" + cou + '/' + zip_in.val(),
                    cache: false,
                    dataType: "json",
                    type: "GET",
                    success: function (result, success) {
                        // Make the city and state boxes visible
                        places = result['places'][0];
                        jQuery("#billing_city").val(places['place name']);
                        jQuery("#billing_state").replaceWith('<input class="form-control" type="text" name="billing_state" id="txtCity" />');
                        jQuery("#txtCity").val(places['state']);
                        jQuery("#billing_state_field .select2").hide();
                        zip_box.addClass('success').removeClass('error');
                    },
                    error: function (result, success) {
                        zip_box.removeClass('success').addClass('error');
                    }
                });
            }
        });
    });

You Can also refer Below link as well

See the Pen bvaYvW by Parth (@parths267) on CodePen.