How to make state city select list with ajax and PHP?

PHP jQuery |16/09/2019 09:40 | 394 show | 0 comment(s)
How to make state city select list with ajax and PHP?

How to make state city select list with ajax and PHP ?

I would like to share with you the ajax state city listing application that I use in most of my projects. This system is used in many e-commerce sites and automation applications. You can use it in your own projects.

Starting from zero, I'm going to give you a detailed step-by-step description of html, mysql and jquery so you can easily incorporate them into your projects. Let's take action, take our keyboard.

What is the minimum level of knowledge to be able to implement state city list with ajax?

You must have at least a minimum knowledge of html, php, and jquery to successfully implement what is described in this article.

 

Step 1: Upload a Table to the Database

Let's finish the database section first. To do this, download the state_city.sql file and upload it to our mysql database. I looked for a lot of information in this painting, I worked hard. I hope it's true :)

I created a database named "addressing" with the character set "utf8_unicode_ci". I uploaded the file "state_city.sql" to the database.

When you successfully export the file to the database, you will see a table like the picture below. If you do not see a table like the following, the database does not exist. Try again. 

ajax state city listing 1

 

 

Step 2: Create a state city listbox with HTML codes

If we survived the database section without any problems, we will now look at the "Bootstrap". Let's take the simplest template and create a dropdown list with html codes.

I used version 3.4 of "Bootstrap". Of course you can choose according to yourself. We get "Basic template"  from "Getting started" page. We will perform our operations using the simplest template. 

When we create the template, we go to the “Forms” tab from the “CSS” page and create a simple form. We will use 2 labels and 2 select lists in this form.

Here are the codes of our "index.php" page:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>State City Selection with PHP Ajax</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>

<div class="container">
    <h1>State City Selection</h1>

    <form class="form-horizontal">
        <div class="form-group">
            <label for="il" class="col-sm-2 control-label">State</label>
            <div class="col-sm-10">
                <select class="form-control" id="state" name="state">
                    <option value="0">Select State</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label for="city" class="col-sm-2 control-label">City</label>
            <div class="col-sm-10">
                <select class="form-control" id="city" name="city">
                    <option value="0">Select City</option>
                </select>
            </div>
        </div>
    </form>
</div>

<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
</body>
</html>

ajax state city listing 2

As a result of these codes we need to get a look like the picture. However, they do not connect with php mysql and jquery, so they seem empty. If we have done this without any problems, we can start writing the php code.

 

Step 3: Making "connection.php", "addressing.php" pages

We use pdo to establish a connection so that we can prevent minor vulnerabilities that may arise from the security part. In most sites mysql_ commands remained obsolete contents. I'm thinking of you. Switch to pdo, do not allow sql injection. :)

We will create a php page named "connection.php" and link the database to our project. We wrote our database name in Step 1, it will be “addressing”. The user name is "root" and the password is empty because I work at localhost. You change the relevant parts according to your system.

"connection.php" page codes:

$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "addressing";

try {
    $db = new PDO("mysql:host={$DB_host};dbname={$DB_name};charset=utf8", $DB_user, $DB_pass);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo $e->getMessage();
}

In the background, according to the change of the state by post method will be taken to the city. To do this, create the “addressing.php” page. If there is a state_id on this page, the cities belonging to the relevant state_id from the database will be returned in json format.

"addressing.php" page codes:

require_once 'connection.php'

$state_id = $_POST['state'];
if(isset($state_id)){

    if($state_id>0) {

        $city   = $db->query("SELECT DISTINCT city_id, city FROM addressing WHERE state_id='$state_id' ORDER BY city_id ASC");
        $begin  = '[{"city_id": "", "city": "Select City"},'
        $end    = ']'
        $list   = ''

        while($row = $city->fetch(PDO::FETCH_ASSOC)){
            $list.='{"city_id": '.$row['city_id'].', "city": "'.$row['city'].'"},'
        }
        echo $begin.rtrim($list,",").$end;
    }
}

ajax state city listing 3

 

 

Step 4: Using jQuery ajax to pull state and city selection to our html page

Let's include state and city selection in our "index.php" page. The first thing we need to do here is to call the "connection.php" page. In this way, we will access the database. We will then pull the state list and print the first select list. Then I will print the second select list in the city list with jquery ajax. The content of the city list will be updated with each state change.

The latest version of "index.php":

require_once 'connection.php'

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>State City Selection with PHP Ajax</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>

<div class="container">
    <h1>State City Selection</h1>

    <form class="form-horizontal">
        <div class="form-group">
            <label for="il" class="col-sm-2 control-label">State</label>
            <div class="col-sm-10">
                <select class="form-control" id="state" name="state">
                    <option value="0">Select State</option>
                    <?php
                    $stateResult = $db->query("SELECT DISTINCT state_id, state FROM addressing ORDER BY state_id ASC");
                    while($row = $stateResult->fetch(PDO::FETCH_ASSOC)){
                        echo '<option value="'.$row['state_id'].'">'.$row['state'].'</option>'
                    }
                    ?>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label for="city" class="col-sm-2 control-label">City</label>
            <div class="col-sm-10">
                <select class="form-control" id="city" name="city">
                    <option value="0">Select City</option>
                </select>
            </div>
        </div>
    </form>
</div>

<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
<script>
    //In this code, the city selection list is disabled.
    $("#city").attr("disabled", "true");

    //If the state selection changes, the following operations are performed.
    $("#state").change(function()
    {
        var state = $(this).val();

        if(state > 0) {
            // If "state_id" is greater than zero, "city" select will be selectable and the options in "city" will be deleted.
            $("#city").removeAttr("disabled");
            $("#city option").remove();

            // After this process, we will make city selection with ajax.
            // Let's do the addressing.php page.
            /*
                We send the state_id to the "addressing.php" page by post method. We're getting the Json dump.
                If the process is correct, we will print the cities in the #city select list.
             */
            url = "addressing.php";
            $.ajax({
                type    : "post",
                url     : url,
                dataType: "json",
                data    : {
                    state : state
                },
                success : function (response) {
                    var cities = response;

                    for(var city in cities) {
                        $(cities[city]).each(function(index, value) {
                            $("#city").append('<option value="' + value.city_id + '">' + value.city + '</option>');
                        });
                    }
                },

                error: function (response) {
                    console.log("Error: Addressing ajax.");
                    console.log(response);
                }
            });

        } else if(il < 1) {
            // If state_id is less than 1, then the county will become unselectable again. Options within the city will be cleared again. Just "Select city" option will come.
            $("#city").attr("disabled", "true");
            $("#city option").remove();
            $("#city").append('<option value="">Select City</option>');
        }
    });
</script>
</body>
</html>

ajax state city listing 4

 

Now that we have completed all the steps, we have successfully selected the state city drop down list using jquery ajax. If you have any problems, if you type the error you're experiencing in the comments section below, I'm ready to help you. You can share them with friends so they can be included in their system. Goodbye and health.

Project source files: download

Report Reaction




Share




Subscribe


Comments (0 )

Add Comment

Enter your name, surname, email and comment, we will post at the end of the review.
Yukarı Çık