I cannot read the json PHP-encoded array

Asked

Viewed 447 times

1

I’m not getting in jQuery Ajax to read this array encoded with PHP:

[{"voo_Cod":"1","voo_CidadeOrigem":"1","voo_CidadeDestino":"2","voo_Data":"2015-07-13 07:00:00","voo_Preco":"200"}]

My code in jquery,

       <script>
        $(function() {
            $("#form").on("submit", function(event) {
                event.preventDefault();

                $.ajax({
                    url: "dadosJSON.php",
                    // dataType: "json",
                    type: "post",
                    data: $(this).serialize(),//manda os arquivos em linha
                    success: function(d) {
                        alert(d);


        //testa se exista dados
         if(d[0].erro){
         $("h2").html(d[0].erro);
        } else{
        var html = "";     
        // var html =alert(d);
        // executo este laço para ecessar os itens do objeto javaScript
        for($i=0; $i < d.length; $i++){
            html += " <strong>Voo Data e Horario</strong> "+ d[$i].voo_Data;

            html += " <strong>Preco</strong> "+ d[$i].voo_Preco;
        }//fim do laço  

      }//fim do else


        $("body").html(html); 

                });
            });
        });


    </script>

My code in PHP:

 <?php
// header('Content-Type: application/json; charset=utf8');
require_once("./authSession.php");
require_once("./conf/confBD.php");
include_once("../html/cabecalho_main_Pessoal.html");



$nomeUser = ($_SESSION['nomeUsuario']);
 //teste
//print_r($_POST);// you will get an array of all the values


try{
    $conexao = conn_mysql();
}catch(PDOException $excep){
    echo "Erro!: " . $excep->getMessage() . "\n";
    die();
}


if(!empty($_POST['cidadeOrigem'])){
    $cidOrigem   =  utf8_encode(htmlspecialchars($_POST['cidadeOrigem']));
    $CidDestino  =  utf8_encode(htmlspecialchars($_POST['cidadeDestino']));
    //$passageiros =  utf8_encode(htmlspecialchars($_POST['Passageiros']));
    echo "Contém arquivos";
}else{ echo "Não contém arquivos";}

// Captura os voos disponiveis no banco de dados instrução SQL básica (sem   restrição de nome), 
    $SQLSelect = 'SELECT * FROM voos WHERE voo_CidadeOrigem=? AND   voo_CidadeDestino= ?';

    //prepara a execução da sentença
    $operacao   =  $conexao -> prepare($SQLSelect);

    $pesquisar  =  $operacao -> execute(array($cidOrigem, $CidDestino));

    //$resultados =  $operacao -> fetchAll();//resultado antigo

    $resultados = $operacao->fetchAll(PDO::FETCH_ASSOC);//resultado com array associativo

    // fecha a conexão (os resultados já estão capturados)
    $conexao = null;    



$dados_result = json_encode($resultados);
echo $dados_result;

?>

My answer creates a loop, with the indefinite variables.

Flight Date and Time Undefined Preco Undefined

Contains files

[{"voo_Cod":"1","voo_CidadeOrigem":"1","voo_CidadeDestino":"2","voo_Data":"2015-07-13 07:00:00","voo_Preco":"200"}]

In the log console, displays the code below

 <!DOCTYPE html>
<html lang="pt-br">
<head>
   <meta charset="UTF-8">
   <title>SISTEMA DAW TURISMO</title>   

   <script    src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

   <link rel="stylesheet" type="text/css" href="../CSS/estiloCabecalho.css">

   <link rel="stylesheet" type="text/css" href="../CSS/estilo_login_teste.css">

   <link rel="stylesheet" type="text/css" href="../CSS/estilo_cadastro.css">

    <!--! funciona pra agenda lettering-->
   <link href="../css/starter-template.css" rel="stylesheet">

   <!-- Importando JavaScript -->
   <!-- <script type="text/javascript" src="../JS/ajax_Jquery.js"></script>-->




        <script>


       $(function() {
        $("#form").on("submit", function(event) {
            event.preventDefault();

            $.ajax({
                url: "dadosJSON.php",
                type: "post",
                data: $(this).serialize(),
                success: function(d) {
                    alert(d);

                    if (console) {
                        console.log(d);
                    }

                    if(d[0] && d[0].erro){
                        $("h2").html(d[0].erro);
                    } else {
                        var html = "", j = d.length;
                        for(var i=0; i < j; i++){
                            html += " <strong>Voo Data e Horario</strong> "+   d[i].voo_Data;

                            html += " <strong>Preco</strong> "+    d[i].voo_Preco;
                        }//else fecha
                   }
                    $("body").html(html); 

                            }
                    });
                });
            });




        </script>



</head>



<body>

    <h1>SISTEMA DAW TURISMO</h1>
<nav id="primary_nav_wrap">
<ul>
  <li class="current-menu-item"><a href="./mainPage_Pessoal.php">Home</a>   </li>
  <li><a href="./index.php">Reservas</a></li>
  <li><a href="./alterar_Cadastro.php">Alterar Cadastro</a></li>
  <li><a href="./mainPage_Pessoal.php">Passagens</a></li>
  <li><a href="./hoteis.php">Hotéis</a></li>
   <li><a href="./listarCompras.php">Listar Reservas</a></li>
  <li><a href="./logout.php">Sair</a></li>
  <!-- <li><a href="#">Reservas</a></li>
  <li><a href="#">Contact Us</a></li> -->
</ul>
</nav>

</body>
</html>
  • In Javascript you don’t have the $ to get the index of the Array, you can do it directly like this: d[i]. voo_Preco, without the dollar sign.

  • Thanks Giancarlo, I’ll try this way.

  • I performed the code without the dollar sign, but continued giving Undefined.

  • 1

    Give a.log(d) console instead of Alert and say what comes out in the browser console.

  • bfavaretto, continued giving in browser Flight Date and Time Undefined Price Undefined, really I do not know. Thank you

  • Look at the console (F12), and change Alert to console.log like I said.

  • bfavaretto, I did what you said. I went to the console also did not charge anything, continued giving the loop. It might be the json_encode array?

  • 1

    here bro... change this Alert(d); so console.log(d); But look, this is not a solution .. is just to better read the return of ajax within the browser console debug.. .

Show 3 more comments

2 answers

1


If I understand well the problem may be in PHP, so add the header in your PHP like this:

dadJSON.php:

<?php
header('Content-Type: application/json; charset=utf8');

//Resto do seu código PHP abaixo

Change the charset as needed

And I recommend using a good indentation and always use the var when declaring variables, also always recommend set the .length in a variable and not within the loop and instead of alert use console.log to debug the code:

    $(function() {
        $("#form").on("submit", function(event) {
            event.preventDefault();

            $.ajax({
                url: "dadosJSON.php",
                type: "post",
                data: $(this).serialize(),
                success: function(d) {
                    alert(d);

                    if (console) {
                        console.log(d);
                    }

                    if(d[0] && d[0].erro){
                        $("h2").html(d[0].erro);
                    } else {
                        var html = "", j = d.length;
                        for(var i=0; i < j; i++){
                            html += " <strong>Voo Data e Horario</strong> " + d[i].voo_Data;

                            html += " <strong>Preco</strong> " + d[i].voo_Preco;
                        }
                    }
                    $("body").html(html); 
                }
            });
        });
    });

Note that now the alert(d) will show [Object object]

To view the data sent to the console use the hotkeys Command + Option + J (Mac) or Ctrl + Shift + J (Windows/Linux).


Updating

According to the output of console.log the file dataJSON.php is returning the body of an HTML.

You cannot mix HTML with JSON this way, see that you added this:

include_once("../html/cabecalho_main_Pessoal.html");

Which is probably an HTML, but your answer has to be JSON, mixing HTML with JSON will make the interpreter unable to "parse" the json, so remove what you will not use.

Note also that the error messages should be json, try so:

<?php
header('Content-Type: application/json; charset=utf8');
require_once("./authSession.php");
require_once("./conf/confBD.php");

$nomeUser = ($_SESSION['nomeUsuario']);
 //teste
//print_r($_POST);// you will get an array of all the values


try{
    $conexao = conn_mysql();
}catch(PDOException $excep){
    echo json_encode(array("Erro!: " . $excep->getMessage() . "\n"));
    die();
}

if(!empty($_POST['cidadeOrigem'])){
    $cidOrigem   =  utf8_encode(htmlspecialchars($_POST['cidadeOrigem']));
    $CidDestino  =  utf8_encode(htmlspecialchars($_POST['cidadeDestino']));
    //$passageiros =  utf8_encode(htmlspecialchars($_POST['Passageiros']));
} else {
   echo json_encode(array("Não contém arquivos"));
   die();
}

// Captura os voos disponíveis no banco de dados instrução SQL básica (sem   restrição de nome), 
    $SQLSelect = 'SELECT * FROM voos WHERE voo_CidadeOrigem=? AND   voo_CidadeDestino= ?';

    //prepara a execução da sentença
    $operacao   =  $conexao -> prepare($SQLSelect);

    $pesquisar  =  $operacao -> execute(array($cidOrigem, $CidDestino));

    //$resultados =  $operacao -> fetchAll();//resultado antigo

    $resultados = $operacao->fetchAll(PDO::FETCH_ASSOC);//resultado com array associativo

    // fecha a conexão (os resultados já estão capturados)
    $conexao = null;    

$dados_result = json_encode($resultados);
echo $dados_result;
die();
?>

0

The @Guilherme Reply is plausible, apparently this is the problem. As he may have already solved his problem, I rewrote his code without using the $.ajax because it is not the best solution, I did not understand very well what your code does in full, but I did something kind of similar and in GET, but can modify to POST if you prefer, if another day you want to adapt to your projects or if someone wants to use something cleaner in jQuery

HTML:

<script type="text/javascript" language="JavaScript" src="https://code.jquery.com/jquery-latest.js"> </script>
<form id="exemplo">
<input type="submit" value="Simbora" />
</form>
<body>
<h2></h2>
</body>

SCRIPT:

<script>
    $(function() {

        var n = 0;

        var html = "";

            $("form").on("submit", function(event) {

                event.preventDefault();

                    $.getJSON('dadosJSON.php', function(d) {

                        if(!d.voo_Data){

                            $("h2").html(d.erro);

                        } else {

                            //Buscaria todos os dados da JSON.
                            /*$.each(d, function (k,v) {
                                html += " <strong>"+k+":</strong> "+ v +"<br/>";
                            });*/

                            html += " <strong>Voo Data e Horario</strong> "+ d.voo_Data;

                            html += " <strong>Preco</strong> "+ d.voo_Preco;

                            $("body").html(html); 
                        }
                    });
            });
       });


    </script>

PHP:

<?php 
$data = (object)array("voo_Cod"=>"1",
                      "voo_CidadeOrigem"=>"1",
                      "voo_CidadeDestino"=>"2",
                      "voo_Data"=>"2015-07-13 07:00:00",
                      "voo_Preco"=>"200");

echo json_encode($data);

//Erro 
/*
$erro = (object)array("erro"=>"Houve algum problema");

echo json_encode($erro);*/
  • Thank you Cassiano. Actually the code is a request to the database, where it rescues the data in PDO... fetchAll(PDO::FETCH_ASSOC). I believe the difficulty I am finding is to find the json_encode data. I will post the code in PHP.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.