How to Auto select dropdown with jQuery AJAX

How to Auto select dropdown with jQuery AJAX

How to Auto select dropdown with jQuery AJAX

1. Create Databases
CREATE TABLE `country_state_city` (
  `id` int(11) NOT NULL,
  `country` varchar(250) NOT NULL,
  `state` varchar(250) NOT NULL,
  `city` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `country_state_city`
--

INSERT INTO `country_state_city` (`id`, `country`, `state`, `city`) VALUES
(1, 'Cambodia', 'Phnom Penh', 'Teok Tlar'),
(2, 'Cambodia', 'Phnom Penh', 'Teok laork'),
(3, 'Cambodia', 'Battambang', 'Battambang Municipality'),
(4, 'Cambodia', 'Kampong Cham', 'Kampong Cham 1'),
(5, 'Cambodia', 'Koh Kong', 'Koh Kong 1'),
(6, 'Cambodia', 'Koh Kong', 'Koh Kong 2'),
(7, 'Cambodia', 'Takeo', 'Takeo 1'),
(8, 'Cambodia', 'Takeo', 'Takeo 2'),
(9, 'Cambodia', 'Takeo', 'Takeo 3'),
(10, 'Thailand', 'Amnat Charoen', 'Amnat Charoen 1'),
(11, 'Thailand', 'Amnat Charoen', 'Amnat Charoen 2'),
(12, 'Thailand', 'Amnat Charoen', 'Amnat Charoen 3'),
(13, 'Thailand', 'Amnat Charoen', 'Amnat Charoen 4'),
(14, 'Viet Nam', 'Bac Kan', 'Bac Kan 0'),
(15, 'Viet Nam', 'Bac Kan', 'Bac Kan 1'),
(16, 'Viet Nam', 'Bac Kan', 'Bac Kan 2'),
(17, 'Viet Nam', 'Bac Kan', 'Bac Kan 3');

-- --------------------------------------------------------

--
-- Table structure for table `data_counrty`
--

CREATE TABLE `data_counrty` (
  `id` int(6) NOT NULL,
  `country` varchar(40) NOT NULL,
  `cityProvince` varchar(40) NOT NULL,
  `district` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `data_counrty`
--

INSERT INTO `data_counrty` (`id`, `country`, `cityProvince`, `district`) VALUES
(10, 'Thailand', 'Amnat Charoen', 'Amnat Charoen 2'),
(11, 'Viet Nam', 'Bac Kan', 'Bac Kan 0'),
(12, 'Cambodia', 'Battambang', 'Battambang Municipality');

-- --------------------------------------------------------

--
-- Table structure for table `tbl_country`
--

CREATE TABLE `tbl_country` (
  `id` int(6) NOT NULL,
  `iso` varchar(6) NOT NULL,
  `country_name` varchar(20) NOT NULL,
  `country_nicename` varchar(40) NOT NULL,
  `iso3` varchar(30) NOT NULL,
  `currency_name` varchar(20) NOT NULL,
  `number_code` int(10) NOT NULL,
  `phone_code` int(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `tbl_country`
--

INSERT INTO `tbl_country` (`id`, `iso`, `country_name`, `country_nicename`, 
`iso3`, `currency_name`, `number_code`, `phone_code`) VALUES
(1, 'KH', 'CAMBODIA', 'Cambodia', 'KHM', 'KHR', 116, 855),
(2, 'TH', 'THAILAND', 'Thailand', 'THA', 'THB', 764, 66),
(3, 'VN', 'VIET NAM', 'Viet Nam', 'VNM', 'VND', 704, 84);

2. countryForm.php
?php
    // include file
    include 'assets/connection/connection.php';
    include 'insert.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Country Form</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

   <!-- library -->
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/
            ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/
             css/dataTables.bootstrap4.min.css">

    <!-- add style css name table user -->
    <link rel="stylesheet" href="assets/css/table-user.css" type="text/css">

    <!-- library bootstrap -->
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js">
     </script>
    <script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js">
    </script>


  <!-- include file css and javascript -->
  <link rel="stylesheet" href="assets/css/register-user.css" type="text/css">

</head>
<body>
    <br>

    <div class="container">
        <div class="border-card-form">
            <div class="container-fluid ">         
                <?php 
                    //include select query
                    include 'query_data.php';
                ?>
                <br>
                <!-- country -->
                <h3 class="text-bold text-center">1. Country Information</h3>
                <br>
                <form action="" method="POST"​ enctype="multipart/form-data">
                    <div class="form-group row"> <!--form-group row -->
                        <label for="colFormLabel" class="col-sm-3 col-form-label">
Country <span class="star-red">*</span></label>
                            <div class="col-sm-9">
                       <select class="custom-select mr-sm-2 form-control action"
 name="country" id="country">
                                <option selected>Pleas country select</option>
                                <?php echo $country; ?>
                            </select>
                            </div>
                        </div>
                        <!-- end country -->

                        <!-- city/province -->
                        <div class="form-group row">
                        <label for="colFormLabel" class="col-sm-3 col-form-label">
City/province <span class="star-red">*</span></label>
                            <div class="col-sm-9">
                        <select class="custom-select mr-sm-2 form-control action"
 name="cityProvince" id="cityProvince">
                                <option selected>Pleas province select</option>
                                
                            </select>
                            </div>
                        </div>
                        <!-- end city/province -->

                        <!-- district -->
                        <div class="form-group row">
                        <label for="colFormLabel"
 class="col-sm-3 col-form-label">District
 <span class="star-red">*</span></label>
                            <div class="col-sm-9">
                            <select class="custom-select mr-sm-2 form-control"
 name="district" id="district">
                                <option selected>Pleas select</option>
                            </select>
                            </div>
                        </div>
                         <!-- end district -->

                    <!-- button save -->         
                    <div class="clearfix">
                        <input type="submit" name="save" id="save"
 class="btn btn-primary btnNext float-left" value="Save">
                    </div>
                </form>
            </div>
        </div>
    </div>

    <br>
    
    <?php 
        // select data 
      $mysqli_query = mysqli_query($databaseServer,"SELECT * FROM `data_counrty` ");
    ?>

    <div class="container">  
        <div class="container-fluid ">         
            <!-- border card -->
            <!-- echo message -->
            <?= $errorMessage ;''?>
            <?= $successMessage ;''?>

            <!-- table user all  -->
            <table id="tableHorizontalWrapper" 
           class="table table-striped table-bordered table-sm text-center" 
           cellspacing="0"width="100%">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Country</th>
                        <th>City/Province </th>
                        <th>District</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>

                <?php
                while($row = mysqli_fetch_array($mysqli_query))
                {
                    ?>
                    <tr>
                        <td><?= $id              = $row['id'] ?></td>
                        <td><?= $country         = $row["country"];?></td>
                        <td><?= $cityProvince    = $row["cityProvince"];?></td>
                        <td><?= $district        = $row["district"];?></td>
                        <td><a href="edit.php?id=<?= $row["id"]; ?>">
                        <button type="button" name="edit" id="delete" 
                        class="edit btn btn-primary btn-sm">Edit</button></a>
                            <a href="delete.php?id=<?= $row["id"]; ?>">
                             <button onClick="return confirm('Are you sure you want 
                             to delete?')" type="button" name="delete" 
                          id="delete" class="delete btn btn-danger btn-sm">
                          Delete</button></a></td>
                    </tr>
                <?php 
                    } 
                ?>
                <?php
                // close connection database
                mysqli_close($databaseServer);

                ?>
                </tbody>
                <!-- table dody -->
                <tfoot>
                    <tr>
                        <th>ID</th>
                        <th>Country</th>
                        <th>City/Province </th>
                        <th>District</th>
                        <th>Action</th>
                    </tr>
                </tfoot>
                <!-- end table foodter -->
            </table>
        </div>
    </div>

    <!-- scritp javascript -->
    <script src="assets/js/javascript.js" type="text/javascript"></script>
</body>
</html>

3.delete.php
<?php
// connection database
include 'assets/connection/connection.php';

    $id   =   $_REQUEST['id'];
    
    // sql to delete a record
    $deleteData = "DELETE FROM `data_counrty` WHERE `data_counrty`.`id` = $id";

    // check query
    if ($databaseServer->query($deleteData) === TRUE)
    {
        
    //success message
    $successMessage = '<div class="alert alert-success text-center" 
     role="alert">Record deleted successfully.</div>';
    }
    else
    {
    // error message
    $errorMessage   = '<div class="alert alert-secondary text-center" 
    role="alert">Error deleting record.</div> ' . $insertData . "<br>" 
. $databaseServer->error;

    }

    header("Location: countryForm.php");

// close connection database
$databaseServer->close();

4.edit.php
  <?php
    // connection database
    include 'assets/connection/connection.php';

    // query edit
    $id           =   $_REQUEST['id'];
    $mysqli_query = "SELECT * FROM `data_counrty` WHERE id ='". $id ."'"; 
    $result       = mysqli_query($databaseServer, $mysqli_query) 
    or die ( mysqli_connect_error());
    $row          = mysqli_fetch_assoc($result);

    // select query option dropdown
    $country = mysqli_query($databaseServer, 
    "SELECT DISTINCT country FROM country_state_city");
    $cityProvince = mysqli_query($databaseServer,
    "SELECT DISTINCT state FROM country_state_city");
    $district = mysqli_query($databaseServer,
    "SELECT DISTINCT district FROM data_counrty");
   
    // isset edit    
    if(isset($_POST['new']) && $_POST['new']==1)
    {
      
        $country                =   $_REQUEST['country'];
        $cityProvince           =   $_REQUEST['cityProvince'];
        $district               =   $_REQUEST['district'];
       
        $updateData = "UPDATE `data_counrty`SET country = '".$country ."',
           cityProvince  = '" . $cityProvince ."', district = '".$district."'
            WHERE `data_counrty`.`id` = '".$id."'";

        mysqli_query($databaseServer, $updateData) or die(mysqli_connect_error());

        // check query
        if ($databaseServer->query($updateData) === TRUE)
        {
            //success message
            $successMessage = '<div class="alert alert-success text-center" 
            role="alert">Record updated successfully.</div>';
        } 
        else
        {
            // error message
            $errorMessage   = '<div class="alert alert-secondary text-center" 
             role="alert">Error updating record.</div> ' . $updateData . "<br>" 
. $databaseServer->error;
        }
        // display go to list table
        header("Location: countryForm.php");
      
    // close connection database
    $databaseServer->close();
    }
    else
    {
?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>edit-register-User-Form</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- library bootstrap -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/
                       4.3.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/
                      jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/
                      bootstrap.min.js"></script>

        <!-- include file css and javascript -->
        <link rel="stylesheet" href="assets/css/register-user.css" type="text/css">
        <!-- <msdropdown> -->
        <link rel="stylesheet" type="text/css" href="assets/css/dd.css" />

        <!-- </msdropdown> -->
        <link rel="stylesheet" type="text/css" href="assets/css/flags.css" />
    </head>
    <body>

        <br>
        <div class="container">
            <div class="border-card-form">
                <div class="container-fluid ">
                    
                        <!-- echo message -->
                        <?= $errorMessage ;''?>
                        <?= $successMessage ;''?>

                        <h3 class="text-bold">1. Personal Information</h3>
                        <form action="" method="POST"​ enctype="multipart/form-data">

                        <input type="hidden" name="new" value="1" />
                        <input name="id" type="hidden" value="<?= $row['id'];?>" />  

                        <!-- country -->
                        <div class="form-group row"> <!--form-group row -->
                            <label for="colFormLabel" 
                              class="col-sm-3 col-form-label">Country 
                              <span class="star-red">*</span></label>
                                <div class="col-sm-9">
                      <select class="custom-select mr-sm-2 form-control action"
                                      name="country" id="country">
                                    <option selected>Pleas select</option>
                                    <?php foreach($country as $rows):?>
                                    <option value="<?php echo $rows['country']; ?>"
                             <?php if($row['country']==$rows['country']) 
                          echo 'selected="selected"'; ?>>
                              <?php echo $rows['country']; ?></option>
                                    <?php endforeach;?>
                                </select>
                                </div>
                            </div>
                            <!-- end country -->

                            <!-- city/province -->
                            <div class="form-group row">
                           <label for="colFormLabel" class="col-sm-3 col-form-label">
                                City/province <span class="star-red">*</span></label>
                                <div class="col-sm-9">
                          <select class="custom-select mr-sm-2 form-control action"
                                    name="cityProvince" id="cityProvince">
                                    <option selected>Pleas select</option>
                                    <?php foreach($cityProvince as $rows):?>
                                    <option value="<?php echo $rows['state']; ?>"
                   <?php if($row['cityProvince']==$rows['state']) 
                       echo 'selected="selected"'; ?>>
                      <?php echo $rows['state']; ?></option>
                                    <?php endforeach;?>
                                </select>
                                </div>
                            </div>
                            <!-- end city/province -->

                            <!-- district -->
                            <div class="form-group row">
                                <label for="colFormLabel" class="col-sm-3 col-form-label">
                                 District <span class="star-red">*</span></label>
                                <div class="col-sm-9">
                                <select class="custom-select mr-sm-2 form-control" 
                                    name="district" id="district" value="<?= $row['district']; ?>">
                                    <option selected>Pleas select</option>
                                    <?php foreach($district as $rows):?>
                                    <option value="<?php echo $rows['district']; ?>"
                                 <?php if($row['district']==$rows['district']) 
                                    echo 'selected="selected"'; ?>><?php echo $rows['district']; ?></option>
                                    <?php endforeach;?>
                                </select>
                                </div>
                            </div>
                            <!-- end district -->

                            <!-- button save -->         
                            <div class="clearfix">
                                <input type="submit" name="update" 
                                id="update" class="btn btn-primary btnNext float-left" value="update">
                            </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <!-- scritp javascript -->
        <script src="assets/js/javascript.js" type="text/javascript"></script>
        <script src="assets/js/jquery.dd.min.js"></script>
<?php
 } 
?>

5.getcountry.php
<?php
// connection database
include 'assets/connection/connection.php';

//getcountry.php
if(isset($_POST["action"]))
{
    $output = '';
    if($_POST["action"] == "country")
    {
        $query = "SELECT state FROM country_state_city 
                  WHERE country = '".$_POST["query"]."' GROUP BY state";
        $result = mysqli_query($databaseServer, $query);
        $output .= '<option value="">Please select Province</option>';
        while($row = mysqli_fetch_array($result))
    {
        $output .= '<option value="'.$row["state"].'">'.$row["state"].'</option>';
    }
}
    if($_POST["action"] == "cityProvince")
    {
        $query = "SELECT city FROM country_state_city 
                  WHERE state = '".$_POST["query"]."'";
        $result = mysqli_query($databaseServer, $query);
        $output .= '<option value="">Please select district</option>';
        while($row = mysqli_fetch_array($result))
        {
            $output .= '<option value="'.$row["city"].'">'
.$row["city"].'</option>';
        }
    }
    echo $output;
}

6.insert.php
<?php
// connection database
include 'assets/connection/connection.php';

// submit data into database
if(isset($_POST['save']))
{
    $country =$_POST['country'];
    $cityProvince =$_POST['cityProvince'];
    $district =$_POST['district'];
    
    // insert data into database
    $insertData = "INSERT INTO `data_counrty`(`country`,`cityProvince`,`district`)
                   VALUES ('".$country."','".$cityProvince."','".$district."')";

    //  query data into database
    if($databaseServer->query($insertData) === TRUE)
    {
        //success message
        $successMessage = '<div class="alert alert-success text-center" 
                           role="alert">New record created successfully.</div>';
    }
    else
    {
        // error message
        $errorMessage   = '<div class="alert alert-secondary text-center"
                         role="alert">Insert error, Please try again.</div> ' 
. $insertData . "<br>" . $databaseServer->error;
    }

    header("Location: countryForm.php");
        
} // end save data insert

// close connection database
$databaseServer->close();

7.query_data.php
<?php
// connection database
include 'assets/connection/connection.php';

// country query
$country = '';
$query = "SELECT country_nicename  FROM tbl_country GROUP BY country_nicename  
          ORDER BY country_nicename  ASC";
$result = mysqli_query($databaseServer, $query);

while($row = mysqli_fetch_array($result))
{
    $country .= '<option value="'.$row["country_nicename"].'">'
.$row["country_nicename"].'</option>';
}

Reactions

Post a Comment

0 Comments

close