Error listing items using JSON and PHP

Asked

Viewed 363 times

0

I am inserting items in a list through a SESSION in PHP, these items will be read in another page using JSON, but 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 registration page data, 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");
            }    
        }
    });
}

Next this is my list page 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 that’s all he brings me

inserir a descrição da imagem aqui

I noticed that in my array it does not bring the comma that separates the objects I think it is but I do not know how to put that comma there.

inserir a descrição da imagem aqui

If you can help me since thank you, because this is a proof of a selection process for a job and I really wanted to get, see you all.

1 answer

3


The error is in the file that displays 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 the for of the code causes the elements to be presented correctly in a Array:

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

The loop you were using traversed each of the items in the collection var and presented each item in format json. That’s why you didn’t see commas on json that was being generated before. Like the jQuery.ajax interprets the json strictly speaking, this may cause an error when executing the request.

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

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

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

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

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

  • Hmm, vlw @Pantera is true. An error has already been fixed but the page that will show JSON still brings back the error I showed in the first image, it enters the error condition and does not succeed.

  • @Alisonpaulo After the changes I indicated the error continues? I imagined that this error was because the file that presents the json was not presenting a json and, according to the official documentation of the jQuery.ajax, if the dataType for "json" and jQuery can’t interpret, an error will be sent.

  • this made the changes, however it enters the error condition, does not enter the sequence

  • @Alisonpaulo, if you visit the Chrome web inspector (usually by pressing the button F12) and open the flap Network and reload the page principal.php some error appears?

  • have yes an error, Not Found..... http://localhost:8080/phpproject1/Desafiojunior/principal.php? _=147519995527%20404%20(Not%20Found)

  • @Alisonpaulo edited the answer. See if it helps you.

  • is on the right track, yes that was it I tbm realized it could be that. So he’s not showing the content in tbody, just appears "loading".

  • @Alisonpaulo this is because you are using the successful callback property with the wrong name, you are using sucess, the correct is success.

  • Kept on going, almost giving up here =(

  • 1

    It worked now @Pantera, vlw ai man the patience and the effort to help !

Show 5 more comments

Browser other questions tagged

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