1
It has been 3 days that I am searching in several sites of the network that deal with this subject a solution to my problem, but I am not able to discover the cause of it.
I come to ask for help from the experts on the subject, because I’m already getting a little desperate with so many frustrated attempts to solve something that in my view should be simple, but that makes me even more bald.
I have tried to treat the return of a query made in PHP that returns a JSON object in a script I will use on a site I am creating, but I can’t access the object layers.
I always see in the console.log of Firefox the following: undefined.
My PHP code is this below and works perfectly by running it alone in the browser, passing the required parameter which is the idPro=XXX.
The code does a database search and returns all products that meet the request.
The return of PHP code is like this:
[
 {"id":"123","descricao":"PRODUTO 1"},
 {"id":"345","descricao":"PRODUTO 2"},
 {"id":"567","descricao":"PRODUTO 3"},
 {"id":"789","descricao":"PRODUTO 4"}
]
In the javascript code I have tried to refer to the object to take the data inside it and show it only in the console.log for now, I have not yet implanted the rest of the code where the data will actually be used, because first I need to make it work in the console.log.
I summed it up a little with the intention of simplifying.
Thank you so much.
Code 1:
$(document).ready(function()
{
	$("input[name='codigo']").bind("change paste keyup blur", function()
	{
		var codigodigitado   =  $('#codigo').val();
		var retorno = '';
		
		console.log( codigodigitado ); // Aqui mostra no console o que eu digitei no campo do form (funciona ok).
		
		$.ajax({
		type: "POST", 
		//dataType: 'json',	//Se eu ativo isso, nada retorna.
		data: {idPro: codigodigitado}, //parâmetro de pesquisa passao ao php (funciona ok).
		url: "busca_descricao.php", 
		beforeSend: function(){
			// Funcionou (coloquei apenas para testar).
			//console.log("Isso executara antes da requisicao"); // funciona ok.
		},
		success: function(responses){
			// Funcionou (mostra corretamente os dados).
			console.log(responses); // Aqui são os dados vindos do PHP (fuciona ok).
			// O problema esta aqui: (não mostra o conteúdo do objeto)
			console.log(responses.id); // undefined (não funcionou).
			console.log(responses[0].id); // undefined (não funcionou).
			console.log(responses["0"].id); // undefined (não funcionou).
			
			
			// Isso será usado depois que eu resolver o problema acima.
			//var options = { 
			//data: responses,
			//getValue: "id"
			//};
	
			//$("#codigo").easyAutocomplete(options);				
			
		}
		});
			
		
	});
});
<input type="text" name="codigo" id="codigo" autocomplete="off" required />
Code 2:
<?php
require("user_ver_login.php");
include("include/admin.php");
include("include/conexao.php");
//
if(isset($_POST['idPro'])) {
	$idPro = $_POST["idPro"];
} elseif(isset($_GET['idPro'])) {
	$idPro = $_GET["idPro"];
} else {
	$data = array();
	$retorno = array_push ( $data ,  array( "id" => "0", "descricao" => utf8_encode( "Nada foi passado!" ) ) );
	$retorno = json_encode($data);
	echo $retorno;  
	exit;
}
//
$idUsu = $_SESSION['idUsubd']; // Pega o ID do usuário
////$sql = "SELECT Descricao,Preco FROM produto WHERE idPro='$idPro' and idUsu='$idUsu'"; // Pega só os produtos do usuário.
$sql = "SELECT idPro,Descricao FROM produto WHERE Descricao like '%$idPro%'"; // Pega todos os produtos (apenas para o teste do json).
$cont = 0;
$result = mysqli_query($conexao, $sql);
$cont = mysqli_num_rows($result);
$data = array();
////$contador = 0;
while($row = mysqli_fetch_row($result)) {
	 array_push ( $data ,  array( "id" => utf8_encode($row[0]), "descricao" => utf8_encode( trim( $row[1] ) ) ) );
	 ////$contador = $contador + 1;
}
if ($cont == 0) {
	$retorno = array_push ( $data ,  array( "id" => "0", "descricao" => utf8_encode( "Produto inexistente!" ) ) );
}
// Converte para o formato json.
////header('Content-Type: application/json'); // não funcionou, dá erro!
$retorno = json_encode($data);
// Retorna o array direto sem converter (apenas um teste).
//$retorno = $data;
echo $retorno;
?>
Hello Gleidson, thank you for your return. I did everything you suggested but without any success. I am very suspicious that it is some fault in my XAMPP. I’ll put all my content on a real web server to see if the result is the same. Once I have something new I put it on. Thank you very much :)
– Sandro Walmor
Please post the result of
console.log(responses);of the Success.– Gleidson Henrique
Gleidson, I managed to fix it. I’ll post the solution. Thank you so much for your help. :)
– Sandro Walmor