简体   繁体   English

JS / PHP-根据先前的选择自动填充选择字段

[英]JS/PHP - auto-populate select fields based on previous selection

SO I have 3 select fields and I would like to populate the #2 and #3 based on the selected value in #1. 所以我有3个选择字段,我想根据#1中的选定值填充#2和#3。

JS is picking up on the field change in #1, submits it successfully to my PHP script, but there I receive an "Array to string conversion" error when inserting the $_POST['problem'] variable into my query to get the related results. JS正在获取#1中的字段更改,已将其成功提交到我的PHP脚本,但是在向查询中插入$ _POST ['problem']变量以获取相关内容时,我收到“数组到字符串转换”错误结果。

I did try json_encode and made sure the original selected value in the first select field (select id="problem") is an array, hence do not understand where the conversion error comes from. 我确实尝试了json_encode并确保在第一个选择字段(选择id =“ problem”)中原始选择的值是一个数组,因此不了解转换错误的来源。

ERROR: 错误:

<b>Notice</b>:  Array to string conversion in <b>Z:\xampp\htdocs\qcisource\ihg\ajax.php</b> on line <b>17</b><br />
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null} 

Any suggestions? 有什么建议么?

HTML 的HTML

        <p>Problem Experienced</p>
        <!-- Problem -->
        <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-warning"></i></span>
            <select id="problem" name="problem" class="form-control select2" multiple="multiple" data-placeholder="Select a Problem">
                <option value=""> </option>
                <?php

                // define query
                $sql = "SELECT Issue, Description FROM qci_problems_index_new ORDER BY Issue";

                // query
                $result = $mysqli->query($sql) or die('<p>Query to get Issue from qci_problems_index_new table failed: ' . mysql_error() . '</p>');

                while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
                    $problem = $row['Issue'];
                    $desc = $row['Description'];
                    echo "<option value=\"$problem\" data-desc=\"$desc\">" . $problem . "</option>\n";
                }

                $result->free();
                ?>

            </select>
        </div>

        <p>Problem Category</p>
        <!-- Problem Category -->
        <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-warning"></i></span>
            <select id="problem_category" name="problem_category" class="form-control select2" multiple="multiple" data-placeholder="Select a Problem Category">
                <option value=""> </option>
                <?php

                // define basic query
                $sql = "SELECT DISTINCT Category FROM qci_problems_index_new ORDER BY Category";

                // query
                $result = $mysqli->query($sql) or die('<p>Query to get Category data from qci_problems_index_new table failed: ' . mysql_error() . '</p>');

                while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
                    $category = $row["Category"];
                    echo "<option value=\"$category\">" . $category . "</option>\n";
                }

                $result->free();
                ?>
            </select>
        </div>

        <p>Department Responsible</p>
        <!-- Department Responsible -->
        <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-bars"></i></span>
            <select id="department" name="department" class="form-control select2" multiple="multiple" data-placeholder="Select a Department">
                <option value=""> </option>
                <?php

                // define basic query
                $sql = "SELECT DISTINCT Department_Responsible FROM qci_problems_index_new ORDER BY Department_Responsible";

                // query
                $result = $mysqli->query($sql) or die('<p>Query to get department_responsible from qci_problems_index_new table failed: ' . mysql_error() . '</p>');

                while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
                    $dept = $row["Department_Responsible"];
                    echo "<option value=\"$dept\">" . $dept . "</option>\n";
                }

                $result->free();
                ?>
            </select>
        </div>

JS JS

<script type="text/javascript" language="javascript"> 
$(function () {
    $('#problem').change(function () {
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: {
                problem: $(this).val()
            },
            dataType: 'json',
            success: function (data)
            {
                var Category = data[0]; 
                var Department_Responsible = data[1];
                $('#problem_category').val(Category);
                $('#department').val(Department_Responsible);
            }
        });
    });  
});  
</script>

ajax.php ajax.php

<?php

if(isset($_POST['problem'])) {

    // Start MySQLi connection
    include './plugins/MySQL/connect_db.php';
    $db = new mysqli($dbhost,$dbuser,$dbpass,$dbname);

    // display error if connection cannot be established
    if($db->connect_errno > 0){
    die('Unable to connect to database [' . $mysqli->connect_error . ']'); }

    // sanitize variables
    $problem = $_POST['problem'];  //mysqli_real_escape throws error, ignore for now

    // run query
    $result = $db->query("SELECT Category, Department_Responsible FROM qci_problems_index_new WHERE Issue= '".$problem."'");

    // return data as array
    $array = mysqli_fetch_array($result);
    echo json_encode($result);

}
?>

Fixed it myself... 我自己修复了...
Apart from some minor mistakes with the JavaScript, the main problem was that I am using the Jquery Select2 plugin which doesn't handle AJAX in the same way that regular <select> fields do. 除了JavaScript的一些小错误外,主要问题是我正在使用Jquery Select2插件,该插件无法以与常规<select>字段相同的方式处理AJAX。 I had to manually trigger('change') on all my fields to get the AJAX value displayed. 我必须在所有字段上手动trigger('change')才能显示AJAX值。

Javascript Java脚本

<script type="text/javascript" language="javascript"> 
$(function () {
    $('#problem').change(function () {
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: 'problem=' + $(this).val(),
            dataType: 'json',
            success: function (data)
            {
            var data0 = data[0]; 
            var data1 = data[1];
            $('#problem_category').val(data0);
            $('#department').val(data1);

            $('#problem_category').trigger('change');
            $('#department').trigger('change'); 
            }
        });
    });  

});  
</script>

Ajax.php Ajax.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if(isset($_POST['problem'])) {

    // Start MySQLi connection
    include '../../plugins/MySQL/connect_db.php';
    $db = new mysqli($dbhost,$dbuser,$dbpass,$dbname);

    // display error if connection cannot be established
    if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']'); }

    // run query
    $sql = "SELECT Category, Department_Responsible FROM qci_problems_index_new WHERE Issue= '".$_POST['problem']."'";
    $result = $db->query($sql) or die(mysqli_error());

    // return data as array
    $array = mysqli_fetch_array($result);
    echo json_encode($array);
}
?>

HTML: HTML:

    <p>Problem Experienced</p>
<!-- Problem -->
<div class="input-group">
    <span class="input-group-addon"><i class="fa fa-warning"></i></span>
    <select id="problem" name="problem" class="form-control select2" data-placeholder="Select a Problem" style="width: 100%;">
        <option value=""> </option>
        <?php

        // define query
        $sql = "SELECT Issue, Description FROM qci_problems_index_new ORDER BY Issue";

        // query
        $result = $mysqli->query($sql) or die('<p>Query to get Issue from qci_problems_index_new table failed: ' . mysql_error() . '</p>');

        while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
            $problem = $row['Issue'];
            $desc = $row['Description'];
            echo "<option value=\"$problem\" data-desc=\"$desc\">" . $problem . "</option>\n";
        }

        $result->free();
        ?>

    </select>
</div>
<p class="help-block" width="100%"><div id="output01" name="output01"></div></p>

<hr />

<p>Problem Category</p>
<!-- Problem Category -->
<select id="problem_category" name="problem_category" class="form-control select2" data-placeholder="Select a Problem Category" style="width: 100%;">
    <option value=""> </option>
    <?php

    // define basic query
    $sql = "SELECT DISTINCT Category FROM qci_problems_index_new ORDER BY Category";

    // query
    $result = $mysqli->query($sql) or die('<p>Query to get Category data from qci_problems_index_new table failed: ' . mysql_error() . '</p>');

    while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
        $category = $row["Category"];
        echo "<option value=\"$category\">" . $category . "</option>\n";
    }

    $result->free();
    ?>
</select>

<hr />

<p>Department Responsible</p>
<!-- Department Responsible -->
<div class="input-group">
    <span class="input-group-addon"><i class="fa fa-bars"></i></span>
    <select id="department" name="department" class="form-control select2" data-placeholder="Select a Department" style="width: 100%;">
        <option value=""> </option>
        <?php

        // define basic query
        $sql = "SELECT DISTINCT Department_Responsible FROM qci_problems_index_new ORDER BY Department_Responsible";

        // query
        $result = $mysqli->query($sql) or die('<p>Query to get department_responsible from qci_problems_index_new table failed: ' . mysql_error() . '</p>');

        while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
            $dept = $row["Department_Responsible"];
            echo "<option value=\"$dept\">" . $dept . "</option>\n";
        }

        $result->free();
        ?>
    </select>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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