Error listing items using JSON and PHP

0

I am inserting items into a list through a SESSION in PHP, these items will be read on another page using JSON, but it is giving error and I am not able to solve.

session_start();
    if(isset($_POST['Cadastrar'])){
        $Nome = $_POST['Nome'];
        $Preco = $_POST['Preco'];
        $Estoque = $_POST['EstoqueInicial'];

        if(!isset($_SESSION['var'])) {
            $_SESSION['var'] = array();
        }
            array_push($_SESSION['var'], array('Nome' => $Nome, 'Preco' => $Preco, 'Estoque' => $Estoque));

    }

Here SESSION receives the html data via POST.

Then I created a session_start () for this page to receive the data from the registration page, this page is what will feed the JSON.

<?php
    session_start();
    header('Content-Type:' . "text/plain");
    if(isset($_SESSION['var'])){
        foreach($_SESSION['var'] as $_SESSION['var']){
            echo json_encode($_SESSION['var'], JSON_PRETTY_PRINT);
        }
    }else{
        echo '[{"erro": "Não foi encontrado nehum registro!"}]';
    }
?>

Here is my AJAX request

function CarregarItens(){
    var itens = "", url = "../dados.php";

    /* Pegando os dado pelo método AJAX*/

    $.ajax({
        url: url,
        cache: false,
        dataType: "json",
        beforeSend: function(){
            $("h2").html("Carregando...");
        },
        error: function(){
            $("h2").html("Há algum problema na leitura dos dados!");
        },
        sucess: function(retorno) {
            if(retorno[0].erro){
                $("h2").html(retorno[0].erro);
            }else{
                /*Laço que cria as linhas da tabela*/
                for(var i = 0; i < retorno.length; i++){
                    itens += "<tr>";
                        itens += "<td>" + retorno[i].Nome + "</td>";
                       // itens += "<td>" + retorno[i].Preco + "</td>";
                        //itens += "<td>" + retorno[i].Estoque + "</td>";
                    itens += "</tr>";  
                }    
                $("#Tabela tbody").html(itens);
                $("h2").html("Carregando");
            }    
        }
    });
}

Then this is my page listing where the JSON magic would happen

<?php
    session_start();
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="js/script.js"></script>
        <script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    </head>
    <body onload="CarregarItens()">
        <selection>
            <!--Área que mostra carregando-->
            <h2></h2>
            <!--Tabela-->
            <table id="Tabela">
                <caption>Cadastro de Produtos</caption>
                <thead>
                    <th>Nome:</th>
                    <th>Preco:</th>
                    <th>Estoque:</th>
                </thead>
                <tbody>
                </tbody>
            </table>
        </selection>
    <a href="dados.php">Listar</a>
    </body>
</html>

But it only brings me this

InoticedthatinmyarrayitdoesnotbringthecommathatseparatestheobjectsIthinkthatisitbutIdonotknowhowtoputthatcommathere.

If you can help me from now thank you, because this is a test of a selective process for a job and wanted very much to achieve, vlw to all.

    
asked by anonymous 30.09.2016 / 00:42

1 answer

2

The error is in the file that presents JSON.

<?php
session_start();
header('Content-Type:' . "application/json");
if(isset($_SESSION['var'])){
    echo json_encode($_SESSION['var'], JSON_PRETTY_PRINT);
}else{
    echo '[{"erro": "Não foi encontrado nehum registro!"}]';
}

Removing for of code causes elements to display correctly in Array :

 [{
    "Nome": "Alison",
    "Preco": "120",
    "Estoque": 1
  },
  {
    "Nome": "Carlinhos",
    "Preco": "125",
    "Estoque": 1
  }]

The repeat loop you were using traversed each of the items in the var collection and presented each item in json format. That's why you did not see commas in the json that was being generated before. Since jQuery.ajax interprets json strictly, this may give you an error executing the request.

Another possibility of error seems to be in the CarregarItens function, in the following line:

var itens = "", url = "../dados.php";

The path you are using to access dados.php appears incorrect. Remove ../ :

var itens = "", url = "dados.php";

The dados.php file seems to be in the same directory as principal.php , where javascript runs. When you use ../ the request will look up the file in the parent directory. And since the file is not there, the request fails.

    
30.09.2016 / 01:08