简体   繁体   中英

Dynamically updating content of drop down menu when radio button value is changed using PHP, MySQL and AJAX

I am creating a form and in it there are two radio buttons and a drop down list. I want when a user changes their choice of radio button, the drop down list also changes its values which will picked from a database table with two columns with names life and general.

Here is a snippet of the request.php

  <input type="radio" name="department" id="department" value="life" onchange="listDept(this.value)" checked>Life <input type="radio" name="department" id="department" value="general">General </td> </tr> <tr> <td></td> <td></td> <td> <select name="department" id="listDept"> </select> 

Here is the getdepartment.php file to query the database:

 <?php require 'connectdb.php'; $department =NULL; if(isset($_POST['department'])){$department = $_POST['department']; } if($department == "life") { $query = "select life from tbl_departments"; $result = mysqli_query($con, $query); while($row = mysqli_fetch_array($result)) echo '<option>'.$row['life'].'</optiom>>'; } if($department == "general") { $query = "select general from tbl_departments"; $result = mysqli_query($con, $query); while($row = mysqli_fetch_array($result)) echo '<option>'.$row['general'].'</option>'; } 

Here is the AJAX script to check the user's choice:

 function listDept() { var dept = document.getElementById("department").value; var xhr; if (window.XMLHTTPRequest) { //Mozilla, Safari... xhr = new XMLHTTPRequest(); } else if (window.ActiveXObject) { //IE8 and older xhr = new ActiveXObject("Microsoft.XMLHTTP"); } var data = "department" + dept; xhr.open("POST", "./parse_files_php/getdepartment.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(data); xhr.onreadystatechange = display_data; function display_data(){ if(xhr.readyState==4){ if (xhr.status==200) { document.getElementById("listDept").innerHTML = xhr.responseText; } else { alert('There was a problem with the request.'); } } } } 

I am not getting any feedback from the server ie the drop down list is not populated.

My database connections are working fine.

In case youre willing to use jquery for the page scripts for that one functionality you can refer to my sample.

HTML:

    <!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="js/jquery-1.11.1.min.js"></script>
        <script>
            $(document).ready(function() {
                $("input[name='department']").click(function() {
                    //console.log($('input:radio[name=department]:checked').val());
                    getSelectOptions($('input:radio[name=department]:checked').val());
                    //AJAX CALL
                });
            });

            function getSelectOptions(radioVal) {
                $.ajax({
                    type: 'POST',
                    url: 'dbo.php',
                    data: {'radioval': radioVal},
                    success: function(data) {
                        //console.log(data);
                        updateSelect(data)
                    }
                });
            }

            function updateSelect(data) {
                var json = $.parseJSON(data);
                console.log(json);
                var selectHTML;
                $.each(json, function(key, value) {
                    console.log(value);
                    selectHTML += "<option value=" + value + ">" + value + "</option>";
                });
                $('#listDept').html(selectHTML);
            }
        </script>
    </head>
    <body>
        <form>
            <input type="radio" name="department" id="department" value="life">Life
            <input type="radio" name="department" id="department" value="general">General 
            <select name="department" id="listDept">
            </select>
        </form>
    </body>
</html>

and my dummy php file that returns the list entries which obviously will contain your database calls and so forth.

dbo.php

<?php
$radio=$_REQUEST['radioval'];
$selectArray=array();
if($radio=='life'){
$selectArray[0]='life1';
$selectArray[1]='life2';
}else if($radio=='general'){
$selectArray[0]='general1';
$selectArray[1]='general2';

}
echo json_encode($selectArray);

Try the sample and let us know if this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM