1

I'm trying to push information from MYSQL, in a PHP File named edit_v and, in my main file "editar_v" I want to fill the input fields inside my forms so after that, user can edit the info related to the vehicle that is stored in my database. For that, I'm using Ajax, so the page doesn't get reloaded/changed.

Here is my main code of 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> 

Inside the same file, i have the following 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>

So in this part of the code, i give the user the option to select one of the available vehicles in the database. After that, i send it to php file in matriculaPHP, and this is working properly.

Now, there is my 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);          

?>

Conclusion: When i execute my code, i get the right values from the database. Example: [{"marca":"Citroen","modelo":"C3","cilindrada":"1100","potencia":"60","combustivel":"Gasolina","ano":"2002","mes":"6","escola_id_escola":"1"}]

But when i try to read the code inside the JSON/Javascript, it gives me the error of UNDEFINED.

I would like to get some of your help so i can solve this problem and keep working in my project.


4
  • 1
    you don't need/should not JSON.stringify data. Use data as it is. console.log(data[0].marca); should get you the right value "Citroen". jQuery assumes it's getting a json back and decodes that to a normal js object already. JSON.stringify would be the wrong way round anyway - if, then JSON.parse(). Commented Nov 3, 2018 at 20:07
  • make sure to also remove the print json_encode($data) line in php. one echo/output is enough. Also best remove the ?> at the end (to avoid extra data beeing sent like a space, a tab, a linefeed) Commented Nov 3, 2018 at 20:11
  • agree with @jeff this should work => $.ajax({ method: "POST", url: "admin_pages/veiculo_pages/edit_v.php", data: {matriculaPHP:strUser}, complete: function(data) { console.log(data[0].marca); }, error : function (data) { console.log("error:"+data.message); console.log("DATA ERROR:: " + data.msg); }, dataType: "JSON", }); Commented Nov 3, 2018 at 20:27
  • Hello guys, thank you for the answers. When i use data[0].marca i get an error saying the following:TypeError: data[0] is undefined and that's why i tried other ways to get the info from ajax. I can't understand the best way to send info from ajax to javascript and get it inside input field. Actually my php code is sending info to complete(data), mas the data, when displayed shows UNDEFINED or Object Object. Commented Nov 5, 2018 at 16:33

3 Answers 3

1

First of all, your edit_v.php file is not outputting valid JSON due to the line that prints the connection status of the database.

If you want to do that then you'll have to output all the data as part of an array.

For example:

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);

Also, the Content-Type header has to be set before any output is made.

In the complete function of your JQuery request, you are converting the JSON data to a String using JSON.stringify(...) which should not be. You should try changing the complete function to success and use the data as is.

...
success: function(data) {
    console.log(data[0].marca);
},
...
Sign up to request clarification or add additional context in comments.

13 Comments

Hello. Actually it gives me the error of: TypeError: data[0] is undefined
@nuno-afonso-silva Can you do console.log(JSON.stringify(data)) and post the results?
Hello! It gives me this answer: {"readyState":4,"responseText":"Base de dados conectada![{\"marca\":\"Citroen\",\"modelo\":\"C3\",\"cilindrada\":\"1100\",\"potencia\":\"60\",\"combustivel\":\"Gasolina\",\"ano\":\"2002\",\"mes\":\"6\",\"escola_id_escola\":\"1\"}][{\"marca\":\"Citroen\",\"modelo\":\"C3\",\"cilindrada\":\"1100\",\"potencia\":\"60\",\"combustivel\":\"Gasolina\",\"ano\":\"2002\",\"mes\":\"6\",\"escola_id_escola\":\"1\"}]\r\n","status":200,"statusText":"OK"} Also the data.msg tells me: undefined
@NunoAfonsoSilva I updated my answer with a few observations. Could you test out the suggestions and let me know what results you get.
OMG Man we did it!!!!! this: console.log('multi array first element', data[0].marca); gets the right output!!! Thank you very much! You and Omari got my code to work!!! I have no words to express how much im grateful!
|
0

Problem is with JavaScript and PHP JSON. When there is only one element in array, there is no record zero. Please use code: console.log(data.marca) instead of console.log(data[0].marca) and you will see result. You have to check if in JSON is just one element array or few and then use proper code.

5 Comments

Hello, Actually it tells me that "marca" doesnt exist. I'm using element inspector in firefox and inside the network the edit_v.php gets the right response from the database and it gets values like: marca:citroen so i think sql query is working well. I just can't understand why javascript/ajax can't get the informations from the php file. Actually i just try to echo or alert them, to verify if they are getting the info from php.
So, could you, send me result of console.log(data) from console in Firefox?
.. and of course let use success not complete method in ajax ..... success: function(data){ console.log('all data',data); console.log('Marca data', data.marca); console.log('multi array first element', data[0].marca); } And check correct answer in console log
With the code from Omari, actually i get this result from data: 0: {…} ​​ ano: "2004" ​​ cilindrada: "1100" ​​ combustivel: "Diesel" ​​ escola_id_escola: "1" ​​ marca: "Peugeot" ​​ mes: "2" ​​ modelo: "206" ​​ potencia: "60" ​​ <prototype>: Object { … } ​ length: 1 ​ <prototype>: Array []
OMG Man we did it!!!!! this: console.log('multi array first element', data[0].marca); gets the right output!!! Thank you very much! You and Omari got my code to work!!! I have no words to express how much im grateful!
0

Solved

finally I solved my problem with the help of this big community!

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;

And now, the PHP file: 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']);
?>

This is working very well, and now I do understand how jquery works in this situations. Also understood what was my fault in PHP.

My thanks to @Omari Celestine and @Norbul and to stackoverflow community.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.