How to make a Cascading Drop Down List in PHP using jQuery

前端 未结 4 1896
终归单人心
终归单人心 2020-11-28 14:43

I have database consists of countries and cities.

First Case - Successfully done:

  1. Country list gets populated in drop box on page load
  2. City li
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 15:40

    index.php

    
    
    
    
        
        StackOverFlow
    
        
        
        
    
    
    
        prepare($sql);
        $stmt->execute();
        ?>
    
        
    
        
    
    
    
    
    
    

    db.php

     PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_PERSISTENT => false,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ));

    get_options.php

    prepare($sql);
    $stmt->execute();
    
    $options = [];
    
    while ($row = $stmt->fetch()){
        $options[] = $row['area'];
    
    }
    
    echo json_encode($options);

    app.js:

    $(document).ready( function(){
    
        $(document).on('change', '.thana-select-box', function(e){
    
            let fd = new FormData();
            let thana = $(this).val();
            fd.append('thana', thana);
            // In this part of the code according to the selected thana, we are going to fetch
            // the rows from the second table Area, the php will return a json structure that contains the  rows
            // or more with the  Area that belong to thana.
    
            $.ajax({
                url: "get_options.php",
                type: "POST",
                data: fd,
                processData: false,
                contentType: false,
    
                complete: function (results) {
                    try {
                        let str = JSON.parse(results.responseText);
                        updateDOM(str);
                        console.log(str)
                    } catch (e) {
                        console.error(e.message);
                    }
                },
            });
    
    
        });
    
    
    
    
        updateDOM = (options) => {
    
            let areaSelectBox = $('.area-select-box');
            let options_dom = '';
            options.map((value)=>{
    
                options_dom += ``;
            });
    
    
            areaSelectBox.html ('');
            areaSelectBox.append(options_dom);
    
    
        };
    
    
    });

提交回复
热议问题