• Home
  • PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
PHP Lift
  • Home
  • Demos
  • Advertisement
PHP Lift
  • Home
  • PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
  • Follow
    • Facebook
    • Twitter
    • Google+
    • Pinterest
    • Youtube
    • Instagram
    • RSS
Make Country, State and City Dropdown with REST API & jQuery
Home
jQuery

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

February 27th, 2022 Huzoor Bux API, jQuery 3 comments

Facebook Twitter Google+ LinkedIn Pinterest

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.

Its using Geodata solution REST API to get data and it’s a very simple and easy-to-use plugin just add HTML in your existing project and enjoy.

jquery plugin for country state city dropdown

ajax country state city dropdown demo

DEMO
DOWNLOAD CODE

Git Repository You can download it from git.

HTML Form:

<form action="" 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 make 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 = type||'json';
        var successRes = function(data) {
            success(data);
        }

        var errorRes = function(e) {
            console.log(e);
        }
        jQuery.ajax({
            url: url,
            type: method,
            data: data,
            success: successRes,
            error: errorRes,
            dataType: type,
            timeout: 60000
        });

    }

}

function locationInfo() {
    var rootUrl = "https://geodata.solutions/api/api.php";
    //now check for set values
    var addParams = '';
    if(jQuery("#gds_appid").length > 0) {
        addParams += '&appid=' + jQuery("#gds_appid").val();
    }
    if(jQuery("#gds_hash").length > 0) {
        addParams += '&hash=' + jQuery("#gds_hash").val();
    }

    var call = new ajaxCall();

    this.confCity = function(id) {
        var url = rootUrl+'?type=confCity&countryId='+ jQuery('#countryId option:selected').attr('countryid') +'&stateId=' + jQuery('#stateId option:selected').attr('stateid') + '&cityId=' + id;
        var method = "post";
        var data = {};
        call.send(data, url, method, function(data) {
        });
    };


    this.getCities = function(id) {
        jQuery(".cities option:gt(0)").remove();
        var stateClasses = jQuery('#cityId').attr('class');

        var cC = stateClasses.split(" ");
        cC.shift();
        var addClasses = '';
        if(cC.length > 0)
        {
            acC = cC.join();
            addClasses = '&addClasses=' + encodeURIComponent(acC);
        }
        var url = rootUrl+'?type=getCities&countryId='+ jQuery('#countryId option:selected').attr('countryid') +'&stateId=' + id + addParams + addClasses;
        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");
            if(data.tp == 1){
                var listlen = Object.keys(data['result']).length;

                if(listlen > 0)
                {
                    jQuery.each(data['result'], function(key, val) {

                        var option = jQuery('<option />');
                        option.attr('value', val).text(val);
                        jQuery('.cities').append(option);
                    });
                }
                else
                {
                    var usestate = jQuery('#stateId option:selected').val();
                    var option = jQuery('<option />');
                    option.attr('value', usestate).text(usestate);
                    option.attr('selected', 'selected');
                    jQuery('.cities').append(option);
                }

                jQuery(".cities").prop("disabled",false);
            }
            else{
                alert(data.msg);
            }
        });
    };

    this.getStates = function(id) {
        jQuery(".states option:gt(0)").remove();
        jQuery(".cities option:gt(0)").remove();
        //get additional fields
        var stateClasses = jQuery('#stateId').attr('class');

        var cC = stateClasses.split(" ");
        cC.shift();
        var addClasses = '';
        if(cC.length > 0)
        {
            acC = cC.join();
            addClasses = '&addClasses=' + encodeURIComponent(acC);
        }
        var url = rootUrl+'?type=getStates&countryId=' + id + addParams  + addClasses;
        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");
            if(data.tp == 1){
                jQuery.each(data['result'], function(key, val) {
                    var option = jQuery('<option />');
                    option.attr('value', val).text(val);
                    option.attr('stateid', key);
                    jQuery('.states').append(option);
                });
                jQuery(".states").prop("disabled",false);
            }
            else{
                alert(data.msg);
            }
        });
    };

    this.getCountries = function() {
        //get additional fields
        var countryClasses = jQuery('#countryId').attr('class');

        var cC = countryClasses.split(" ");
        cC.shift();
        var addClasses = '';
        if(cC.length > 0)
        {
            acC = cC.join();
            addClasses = '&addClasses=' + encodeURIComponent(acC);
        }

        var presel = false;
        var iip = 'N';
        jQuery.each(cC, function( index, value ) {
            if (value.match("^presel-")) {
                presel = value.substring(7);

            }
            if(value.match("^presel-byi"))
            {
                var iip = 'Y';
            }
        });


        var url = rootUrl+'?type=getCountries' + addParams + addClasses;
        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");

            if(data.tp == 1){
                if(presel == 'byip')
                {
                    presel = data['presel'];
                    console.log('2 presel is set as ' + presel);
                }


                if(jQuery.inArray("group-continents",cC) > -1)
                {
                    var $select = jQuery('.countries');
                    console.log(data['result']);
                    jQuery.each(data['result'], function(i, optgroups) {
                        var $optgroup = jQuery("<optgroup>", {label: i});
                        if(optgroups.length > 0)
                        {
                            $optgroup.appendTo($select);
                        }

                        jQuery.each(optgroups, function(groupName, options) {
                            var coption = jQuery('<option />');
                            coption.attr('value', options.name).text(options.name);
                            coption.attr('countryid', options.id);
                            if(presel) {
                                if (presel.toUpperCase() == options.id) {
                                    coption.attr('selected', 'selected');
                                }
                            }
                            coption.appendTo($optgroup);
                        });
                    });
                }
                else
                {
                    jQuery.each(data['result'], function(key, val) {
                        var option = jQuery('<option />');
                        option.attr('value', val).text(val);
                        option.attr('countryid', key);
                        if(presel)
                        {
                            if(presel.toUpperCase() ==  key)
                            {
                                option.attr('selected', 'selected');
                            }
                        }
                        jQuery('.countries').append(option);
                    });
                }
                if(presel)
                {
                    jQuery('.countries').trigger('change');
                }
                jQuery(".countries").prop("disabled",false);
            }
            else{
                alert(data.msg);
            }
        });
    };

}

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();
        }
    });

    jQuery(".cities").on("change", function(ev) {
        var cityId = jQuery("option:selected", this).val();
        if(cityId != ''){
            loc.confCity(cityId);
        }
    });
});

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

country state city drop down list in php mysql

country state city drop down list using javascript in php

Note: In this demo it 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.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Related

  • Tags
  • country
  • state city drop down
Facebook Twitter Google+ LinkedIn Pinterest
Next article How to Convert HTML to PDF in PHP with fpdf
Previous article DataTables Server-side Processing with PHP and MySQL

Huzoor Bux

I am a PHP Developer

Related Posts

Simple PHP REST API with Slim, PHP & MySQL API
March 3rd, 2022

Simple PHP REST API with Slim, PHP & MySQL

DataTables Server-side Processing with PHP and MySQL Guide
February 24th, 2022

DataTables Server-side Processing with PHP and MySQL

How to Find Geolocation by Country IP Address in PHP API
February 22nd, 2022

How to Find Geolocation by Country IP Address in PHP

3 Comments

  1. Nishant Kumar
    October 3, 2021 at 6:20 am Reply ↓

    hello sir thank lot

  2. Shahzaib
    April 19, 2022 at 4:33 pm Reply ↓

    Sir how i can receive that information on email?

    1. Huzoor Bux
      April 20, 2022 at 8:06 am Reply ↓

      Which information?

Leave a Reply to Shahzaib Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Advertisement
    Like us
    Recent Posts
    • How to Create PDFs from HTML with PHP and Dompdf
    • How to create a screen recorder in JavaScript
    • Best 10 Programming Languages that will rule in 2022
    • Top 7 Websites To Get Your First Paid Internship
    • How to Create Bar Chart Race in JavaScript
    Categories
    • API
    • Bootstrap
    • Bot
    • CSS
    • CSS 3
    • Database
    • Designing
    • Framework
    • Guide
    • HTML
    • HTML 5
    • JavaScript
    • jQuery
    • MySQL
    • Node.js
    • oAuth
    • Payment
    • PHP
    • Python
    • Social
    • Tips
    • WordPress
    Weekly Tags
    • PHP
    • How to
    • javascript
    • api
    • MYSQL
    • jQuery
    • HTML to PDF
    • PHP Basics
    • Programming Habits
    • HTML5
    • About
    • Privacy Policy
    • Back to top
    © PHPLift 2021. All rights reserved.