Ajax county select drop down using PHP and MySQL

By David |

PHP |

29th Mar, 2019

Click here to share

Welcome again to Worldtok tutorial.

In this lesson, we are going to be implementing the drop down of ajax country select with drop down in PHP and MySQL.

This tutorial is intended for those that want to learn

1.       How to implement ajax in PHP and MySQL.

2.       How to connect to a database and fetch information from a database using ajax without reloading the page.

3.       The basic JavaScript to implement ajax selection.

This tutorial is easy to follow and will help you to master Ajax, PHP, MySQL and javascript.

To get started download this database and import it to your database.

Download database here

1.       Create a folder called ajax search

2.       Create a file called index.php and copy the following code into it.

 

 

<?php

$connection = new mysqli('localhost', 'root', '', 'phpajax');

if(!$connection){

                die("Database Connection Failed" . $connection->error);

}

 

?>

 

<!DOCTYPE html>

<html>

<head>

                <title>Ajax Country State Select List</title>

                <style type="text/css">

                                #state-select,#city-select{

                                                display: none;

                                }

                </style>

</head>

<body>

<div id="form">

  <h2>Select the Country & State</h2>

    <select id="country-select">

   <option  selected>Please Select Country</option>

           <?php

                      $sql = "SELECT * FROM countries";

                        $result = mysqli_query($connection, $sql);

                                              while($row = mysqli_fetch_assoc($result)){

                                ?>

                                <option value="<?php echo $row['id'] ?>"><?php echo $row['name'] ?></option>

                                <?php } ?>

                </select>

                <br/>

                <select id="state-select">

                               

                </select>

                <select id="city-select">

                               

                </select>

                <script type="text/javascript">

                                function getStatesSelectList(){

                                                var country_select = document.getElementById("country-select");
                                                var city_select = document.getElementById("city-select");

                                               

           var country_id = country_select.value;

            console.log('CountryId : ' + country_id);

 

                                                var xhr = new XMLHttpRequest();

                                                var url = 'states.php?country_id=' + country_id;

                                                // open function

                                                xhr.open('GET', url, true);

                                                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

                                               

                                                // check response is ready with response states = 4

                                                xhr.onreadystatechange = function(){

                                                                if(xhr.readyState == 4 && xhr.status == 200){

                                                                                var text = xhr.responseText;

                                                                                //console.log('response from states.php : ' + xhr.responseText);

                                                                                var state_select = document.getElementById("state-select");

                                                                                state_select.innerHTML = text;

                                                                                state_select.style.display='inline';

                                                                                city_select.style.display='none';

                                                                }

                                                }

 

                                                xhr.send();

                                }

 

                                function getCitySelectList(){

                                                var state_select = document.getElementById("state-select");

 

                                                var state_id = state_select.value;

                                                console.log('StateId : ' + state_id);

 

                                var xhr = new XMLHttpRequest();

                                  var url = 'cities.php?state_id=' + state_id;

                           // open function

                           xhr.open('GET', url, true);

                          xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

                                               

                           // check response is ready with response states = 4

                            xhr.onreadystatechange = function(){

                                                                if(xhr.readyState == 4 && xhr.status == 200){

                                                                                var text = xhr.responseText;

                                                                                //console.log('response from cities.php : ' + xhr.responseText);

                                                                                var city_select = document.getElementById("city-select");

                                                                                city_select.innerHTML = text;

                                                                                city_select.style.display='inline';

                                                                }

                                                }

 

                                                xhr.send();

                                }

 

                                var country_select = document.getElementById("country-select");

                                country_select.addEventListener("change", getStatesSelectList);

 

                                var state_select = document.getElementById("state-select");

                                state_select.addEventListener("change", getCitySelectList);

                </script>

</div>

</body>

</html>

 

Save the file.

create another file under the same folder called states.php and copy and paste the below code in it.

 

<?php

$connection = new mysqli('localhost', 'root', '','phpajax');

if(!$connection){

                die("Database Connection Failed" . mysqli_error($connection));

}

 

$country_id = (int) $_GET['country_id'];

$sql = "SELECT * FROM states WHERE country_id=$country_id";

$result = mysqli_query($connection, $sql);

                echo "<option disabled selected>Please Select State</option>";

while($row = mysqli_fetch_assoc($result)){

                echo "<option value='" . $row['id'] . "'>" . $row['name'] ."</option>";

}

 

?>

 

The above file is the place that will handle the selection of the states based on the valued of the country id passed to it.

 

$country_id = (int) $_GET['country_id'];

 

When the country id is passed, it will be used to retrieve all the states under that country.

The next file will be the city.php.

This file will be used to retrieve all the cities under the selected state. Just like the state selection. State id will be passed it and the result will be used to retrieve all the cities under the selected state without refreshing the page.

Some important thing to highlight about Ajax.

1.       It makes our web application fast.

2.     It increases user experience on our webpage.

To download the full source code see it on GitHub.

If you enjoyed the lesson please give me a star on GitHub and again support us by sharing this lesson with your friends.

 

Leave a Reply

RELATED POSTS


Total of 0 Comment