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.