X
    Categories: APIjQuery

Make Country, State and City Dropdown with REST API & jQuery

Do you need to create a dependent city-state dropdown in your application? You will receive a free download of an AJAX-based dependent code. The selected parent entity determines whether it loads data from the database.

Dropdown options that depend on other inputs can be called dependent dropdowns. Some dropdowns are dependent on timezone, location, and other factors. The linked article provides an example of how to locate users’ locations.

It uses Geodata solution REST API to get data and it’s a straightforward and easy-to-use plugin add HTML to your existing project and enjoy.

jquery plugin for country state city dropdown

ajax country state city dropdown demo

Git Repository You can download it from git.

HTML Form:

<form action-xhr="#" method="post">  

  <div class="container">

    <div class="row">

      <div class="col-sm-4">

        <h3>Country</h3>

        <select name="country" class="countries form-control" id="countryId">

      <option value="">Select Country</option>

  </select>



      </div>

      <div class="col-sm-4">

        <h3>State</h3>

        <select name="state" class="states form-control" id="stateId">

      <option value="">Select State</option>

  </select>

      </div>

      <div class="col-sm-4">

        <h3>City</h3>        

        <select name="city" class="cities form-control" id="cityId">

      <option value="">Select City</option>

  </select>

      </div>

    </div>

  </div>

</form>

This form makes 3 dropdown input in your form Country, State, and City first you have to select county it will extract states for that country then select states and it will extract city names for you.

See Alos: Convert HTML to PDF in Javascript using jsPDF with Example Download

jQuery Code:

function ajaxCall() {

    this.send = function(data, url, method, success, type) {

        type = 'json';

        var successRes = function(data) {

            success(data);

        }

        var errorRes = function(xhr, ajaxOptions, thrownError) {            

            console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);

        }

        jQuery.ajax({

            url: url,

            type: method,

            data: data,

            success: successRes,

            error: errorRes,

            dataType: type,

            timeout: 60000

        });

    }

}



function locationInfo() {

    var rootUrl = "https://geodata.phplift.net/api/index.php";

    var call = new ajaxCall();

    this.getCities = function(id) {

        jQuery(".cities option:gt(0)").remove();

        var url = rootUrl+'?type=getCities&countryId='+ '&stateId=' + id;

        var method = "post";

        var data = {};

        jQuery('.cities').find("option:eq(0)").html("Please wait..");

        call.send(data, url, method, function(data) {

            jQuery('.cities').find("option:eq(0)").html("Select City");

                var listlen = Object.keys(data['result']).length;

                if(listlen > 0)

                {

                    jQuery.each(data['result'], function(key, val) {

                        var option = jQuery('');

                        option.attr('value', val.name).text(val.name);

                        jQuery('.cities').append(option);

                    });

                }

                jQuery(".cities").prop("disabled",false);

        });

    };



    this.getStates = function(id) {

        jQuery(".states option:gt(0)").remove();

        jQuery(".cities option:gt(0)").remove();

        var stateClasses = jQuery('#stateId').attr('class');



        

        var url = rootUrl+'?type=getStates&countryId=' + id;

        var method = "post";

        var data = {};

        jQuery('.states').find("option:eq(0)").html("Please wait..");

        call.send(data, url, method, function(data) {

            jQuery('.states').find("option:eq(0)").html("Select State");

            

                jQuery.each(data['result'], function(key, val) {

                    var option = jQuery('');

                    option.attr('value', val.name).text(val.name);

                    option.attr('stateid', val.id);

                    jQuery('.states').append(option);

                });

                jQuery(".states").prop("disabled",false);

            

        });

    };



    this.getCountries = function() {

        var url = rootUrl+'?type=getCountries';

        var method = "post";

        var data = {};

        jQuery('.countries').find("option:eq(0)").html("Please wait..");

        call.send(data, url, method, function(data) {

            jQuery('.countries').find("option:eq(0)").html("Select Country");

            

            jQuery.each(data['result'], function(key, val) {

                var option = jQuery('');

                

                option.attr('value', val.name).text(val.name);

                option.attr('countryid', val.id);

                

                jQuery('.countries').append(option);

            });

                // jQuery(".countries").prop("disabled",false);

            

        });

    };



}



jQuery(function() {

    var loc = new locationInfo();

    loc.getCountries();

    jQuery(".countries").on("change", function(ev) {

        var countryId = jQuery("option:selected", this).attr('countryid');

        if(countryId != ''){

            loc.getStates(countryId);

        }

        else{

            jQuery(".states option:gt(0)").remove();

        }

    });

    jQuery(".states").on("change", function(ev) {

        var stateId = jQuery("option:selected", this).attr('stateid');

        if(stateId != ''){

            loc.getCities(stateId);

        }

        else{

            jQuery(".cities option:gt(0)").remove();

        }

    });

});



Above jQuery will do the API requests and add data in the dropdown.

country state city drop-down list in PHP MySQL

country state city drop-down list using javascript in PHP

Note: This demo will extract country data from API every time you can fetch it and once and make it static don’t make API calls every time.

Huzoor Bux: I am a PHP Developer

View Comments (17)

      • Access to XMLHttpRequest at 'https://geodata.solutions/api/api.php?type=getCountries&addClasses=form-control' from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

        that is the response i am getting

      • it was not showing countries in the list only displaying "Please wait" but now it is fixed just add ?v2 at the end of src i-e http://countrystatecity.js?v2.

        But Dear brother, can you help me with the option value. its entering the number value number instead of taking the city, state and country name. For example when i submit the page the entry in database for city is showing some number, also for state and country its entering id number. Please help me to enter the name of the city, state and country.

  • it was not showing countries in the list only displaying "Please wait" but now it is fixed just add ?v2 at the end of src i-e http://countrystatecity.js?v2.

    This is very very helpful it was fine before But now with v2, its entering the number value number instead of taking the city, state and country name. For example when i submit the page the entry in database for city is showing some number, also for state and country its entering id number. Please help me to enter the name of the city, state and country.

  • Hi sir, is it possible if I can get the files of data this API is fetching? I want a backup if ever the API goes down just like what happened with geodata.solutions. Thank you

  • Hi Huzoor,

    Thanks a lot for this.

    I couldn't really understand below,

    "Note: This demo will extract country data from API every time you can fetch it and once and make it static don’t make API calls every time."

    Since I am using it in my code for my public website, if people use it then there would be API calls right?

    Is it a matter of concern?

  • Hi ,

    Thanks it works for me but what do you mean by,

    "Note: This demo will extract country data from API every time you can fetch it and once and make it static don’t make API calls every time."

    Vipin