在Wordpress中使用mysql和ajax填充下拉列表

时间:2019-06-21 14:42:38

标签: php jquery mysql ajax wordpress

我有两个下拉菜单。我想使用第一个下拉列表中的结果来填充MySQL查询,然后再填充第二个查询。我正在使用AJAX,因此不必刷新页面。

 <select id="set-reporting-industry" name="set_reporting_industry">
    <option value="" selected disabled>Select Industry</option> <?php

    $industries = $wpdb->get_results( "SELECT id, tag FROM master_tag WHERE cat_id=1 ORDER BY tag ASC" );

    foreach( $industries as $industry ) :

        $industry_id = $industry->id;
        $industry_tag = $industry->tag;

        <option value="<?php echo $industry_id ?>" <?php echo $selected ?>><?php echo $industry_tag ?></option> <?php

    endforeach; ?>
    </select>

    <select id="set-reporting-sector" name="set_reporting_industry">
    <option value="" selected disabled>Select Sector</option> 
    </select>

    <script type="text/javascript">
    jQuery(document).ready(function(){

    jQuery('#set-reporting-industry').change(function(){
    var sectorPOP=jQuery('#set-reporting-industry').val();

    jQuery("#set-reporting-sector").empty();
        jQuery.ajax({
            url:"<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php",
            type:'POST',
            data:'action=populate_edit_location_sector&industryID=' + sectorPOP,

            success:function(results) {
            jQuery("#set-reporting-sector").append(results);
            }
        });
    });
    </script> <?php 

    function populate_edit_location_sector() { echo 'test';

    if( isset( $_POST['industryID'] ) ) :

        $industry_id = $_POST['industryID'];

        global $wpdb;
        $results = $wpdb->get_results( "SELECT master_tag.id, tag FROM master_tag INNER JOIN relation_tag ON master_tag.id=relation_tag.child_id WHERE parent_id=$industry_id ORDER BY tag ASC" );

        foreach( $results as $rows ) :
            echo '<option value="'.$rows->id.'">'.$rows->tag.'</option>';
        endforeach;

        die();
    endif;
    }

    add_action( 'wp_ajax_nopriv_populate_edit_location_sector', 'populate_edit_location_sector' );
    add_action( 'wp_ajax_populate_edit_location_sector', 'populate_edit_location_sector' ); ?>

我的代码什么都不做,没有错误代码

0 个答案:

没有答案