将MYSQL(PHP)值拖入JSON->错误未定义

时间:2018-11-03 20:03:25

标签: javascript php mysql json

我正在尝试从MYSQL在名为edit_v的PHP文件中推送信息,并且在我的主文件“ editar_v”中,我想填写表单内的输入字段,以便在此之后,用户可以编辑与存储在我的数据库中的车辆。为此,我使用的是Ajax,因此不会重新加载/更改页面。

这是我的主要代码 editar_v.php

<div class="container-fluid">
  <div class="row">
      <div class="col-md-12">
        <form method="POST" action="editar_v.php">
            <div class="form-row">
                <div class="form-group col-md-12">
                    <label for="input_veiculo_editar">Escolha o veículo que pretende editar:</label>
                    <select class="custom-select my-1 mr-sm-2" id="dropdown_matricula">   
                    <option selected>Veículos Disponíveis</option>
                    <?php 
                        $conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
                        $sql = "SELECT id, matricula FROM veiculo";
                        $result = $conn->query($sql);

                        if($result->num_rows > 0)
                        {
                            while($row = $result->fetch_assoc()) {
                            echo "<option value='".$row['id']."'>".$row['matricula']."</option>";                      
                            }
                        }    
                    ?>
                    </select>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for"input_marca">Marca do Veículo:</label>
                    <input type="text" class="form-control" id="input_marca" disabled value="NOTHING">
                </div>
                <div class="form-group col-md-6">
                    <label for="input_modelo">Modelo do Veículo:</label>
                    <input type="text" class="form-control" id="input_modelo" disabled>
                </div>
            </div>  
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for"input_cilindrada">Cilindrada (CV):</label>
                    <input type="text" class="form-control" id="input_cilindrada" disabled>
                </div>
                <div class="form-group col-md-6">
                    <label for="input_potencia">Potencia do Veículo:</label>
                    <input type="text" class="form-control" id="input_potencia" disabled>
                </div>
            </div>
            <div class="form-group">
                <label for="input_combustivel">Combustível:</label>
                <input type="text" class="form-control" id="input_combustivel" disabled>
            </div>
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for"input_ano">Ano do Veículo:</label>
                    <input type="text" class="form-control" id="input_ano" disabled>
                </div>
                <div class="form-group col-md-6">
                    <label for="input_modelo">Modelo do Veículo:</label>
                    <input type="text" class="form-control" id="input_modelo" disabled>
                </div>
            </div>  
            <div class="form-group">
                <label for="input_escolaID">Escola de Condução a que pertence:</label>
                <select class="custom-select my-1 mr-sm-2" id="inlineFormCustomSelectPref" disabled>   
                <option selected></option>
                <?php 
                    $conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
                    $sql = "SELECT id_escola, nome FROM escola";
                    $result = $conn->query($sql);

                    if($result->num_rows > 0)
                    {
                        while($row = $result->fetch_assoc()) {
                        echo "<option value='".$row['id_escola']."'>".$row['nome']."</option>";                      
                        }
                    }    
                ?>
                </select>
            </div>
        <input type="button" value="Procurar Veículo" id="procuraveiculo">
        <input type="button" value="Editar Veículo" id="adicionar_veiculo">
        <span id="jsonresultado"></span>
        </form>
      </div>
  </div>
</div> 

在同一文件中,我有以下javascript / jquery:

<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>




<script type="text/javascript">
    $(document).ready(function(){
        console.log("Document ready!");
        $("#procuraveiculo").on('click', function() {
            var e = document.getElementById("dropdown_matricula");
            var strUser = e.options[e.selectedIndex].text;
            alert(strUser);

            $.ajax({
                method: "POST",
                url: "admin_pages/veiculo_pages/edit_v.php",
                data: {matriculaPHP:strUser},

                complete: function(data) {
                    var yourDataStr = JSON.stringify(data);
                    var result = yourDataStr;
                    console.log(result[0].marca);

                },
                error : function (data) {
                    console.log("error:"+data.message);
                    console.log("DATA ERROR:: " + data.msg);
                },
                dataType: "JSON",
            });

        });
    });
</script>

因此,在代码的这一部分中,我为用户提供了选择数据库中可用车辆之一的选项。 之后,我将其发送到matriculaPHP中的php文件中,并且该文件正常工作。

现在,有我的 edit_v.php

<?php

         $conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
         $matricula = $_POST['matriculaPHP'];
         $sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
         $result = $conn->query($sql);

        if($conn->query($sql) == TRUE)
        {
             echo "Base de dados conectada!";
        }
        else
        {
            echo "Error " . $sql . "<br>" . $conn->error;
        }

        $data = array();

        while($row = $result->fetch_assoc()) {
            $data[] = $row;  
        }
        print json_encode($data);
        header('Content-type: application/json');
        echo json_encode($data);          

?>

结论:执行代码时,我从数据库中获取了正确的值。范例:[{“ marca”:“ Citroen”,“ modelo”:“ C3”,“ cilindrada”:“ 1100”,“ potencia”:“ 60”,“ combustivel”:“ Gasolina”,“ ano”:“ 2002 “,” mes“:” 6“,” escola_id_escola“:” 1“}]

但是当我尝试读取JSON / Javascript中的代码时,它给了我 UNDEFINED 错误。

我想得到您的一些帮助,以便我可以解决此问题并继续从事我的项目。


3 个答案:

答案 0 :(得分:1)

首先,由于打印数据库连接状态的行,您的 edit_v.php 文件未输出有效的JSON。

如果要这样做,则必须将所有数据输出为数组的一部分。

例如:

header('Content-type: application/json');

$res = array(
    'success' => false,
    'errors' => array(),
    'data' => null
);

$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo")
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);

if($conn->query($sql) == TRUE)
{
    // echo "Base de dados conectada!";
    $res['success'] = true;
    $res['data'] = array();

    while ($row = $result->fetch_assoc())
    {
        $res['data'][] = $row;
    }
}
else
{
    $res['errors'][] = "Error " . $sql . "<br>" . $conn->error;
}

echo json_encode($data);

此外,在进行任何输出之前,必须先设置Content-Type标头。

在您的JQuery请求的完整功能中,您正在使用JSON.stringify(...)将JSON数据转换为String,而不应该这样做。您应该尝试将complete函数更改为success并按原样使用数据。

...
success: function(data) {
    console.log(data[0].marca);
},
...

答案 1 :(得分:0)

问题出在JavaScript和PHP JSON。 当数组中只有一个元素时,没有记录为零。 请使用代码:console.log(data.marca)而不是console.log(data [0] .marca),您将看到结果。 您必须检查JSON中的元素数组是否只是一个或几个,然后使用正确的代码。

答案 2 :(得分:0)

已解决

最终,我在这个大社区的帮助下解决了我的问题!

Editar_v.php jQuery:

$("#procuraveiculo").on('click', function() {
            var e = document.getElementById("dropdown_matricula");
            var strUser = e.options[e.selectedIndex].text;
            alert(strUser);

            $.ajax({
                method: "POST",
                url: "admin_pages/veiculo_pages/edit_v.php",
                data: {matriculaPHP:strUser},

                success: function(data) {
                    var marca = data[0].marca;
                    var modelo = data[0].modelo;
                    var cilindrada = data[0].cilindrada;
                    var potencia = data[0].potencia;
                    var combustivel = data[0].combustivel;
                    var ano = data[0].ano;
                    var mes = data[0].mes;
                    var idEscola = data[0].escola_id_escola;

现在,PHP文件:edit_v.php:

<?php
header('Content-type: application/json');

$res=array(
    'success' => false,
    'errors' => array(),
    'data' => null
);

$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);

if($conn->query($sql) == TRUE)
{
    // echo "Base de Dados conectada!";
    $res['success'] = true;
    $res['data'] = array();

    while($row = $result->fetch_assoc())
    {
        $res['data'][] = $row;
    }
}
else
{
    $res['errors'][] = "Error " . $sql . "<br>" . $conn->error;
}

echo json_encode($res['data']);
?>

这工作得很好,现在我知道了在这种情况下jquery是如何工作的。还了解我在PHP中的错误。

我感谢@Omari Celestine和@Norbul以及stackoverflow社区。