Error handling a JSON return in AJAX

Asked

Viewed 710 times

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;
?>

2 answers

1

There is a difference between JSON and JSON STRING. If the previous console displays a JSON, but when picking up data from it does not work, it is possibly a string, and needs to be converted to JSON using PARSE. On the Success, put:

responses = JSON.parse(responses)

Although you lost 3 days, don’t be sad, because I have also lost several days in this, and more than once! And I’m sure other people have lost too.

Taking advantage of the topic, I would like to give you another tip that helps me a lot. Whenever you are going to display a JSON on the console, to make it more beautiful, you can do it as follows:

console.log('responses', JSON.stringify(responses, null, 2))

And if you are using VSCODE, you can create a snippet and by entering the prefix cls and press TAB, already writes this console.log.

"Print to console": {
        "scope": "javascript,typescript",
        "prefix": "cls",
        "body": [
            "console.log('$1', JSON.stringify($1, null, 2))"
        ],
        "description": "Console.log com JSON.stringify"
    }
  • 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 :)

  • Please post the result of console.log(responses); of the Success.

  • Gleidson, I managed to fix it. I’ll post the solution. Thank you so much for your help. :)

0

As I had commented earlier, all my suspicions were confirmed. I have migrated my entire project to a WEB server and the result of the.log(Respses) console from Success has returned to JSON correctly. I did several tests and all the valid attempts that were previously frustrated started to work as they should.

So here’s the tip: XAMPP does not work properly with JSON returns.

I will proceed with the development of the project directly on the Web server from now on. It’s a shame, because it was very practical to use XAMPP as localhost, because you didn’t need to use FTP to keep going up the changes all the time.

I always used XAMPP to develop, it works very well with PHP and Mysql, even with Wordpress and in very large projects. But since it was the first time I used jquery on a deeper level, I didn’t even think it could happen.

But I know this is a time slot until you figure it out.

I leave my many thanks to everyone who cooperated. :)

  • Working directly on the server is extremely bad. What if you make the server settings manually instead of using XAMPP, or use another one? It might work, because if it works online, it’s probably just some setup in the place that’s not right. But anyway, I’m glad you made it.

  • 1

    Hi Gleidson, I installed WAMP today and set up all my aliases and folders. In it everything works normally and now I can continue the work that has already been delayed. I thank you for the strength. Thanks! When I have some time I will analyze the XAMPP more calmly to see if I discover the problem, but there are a lot of people in the network who have been through something similar. But no solution. . ;)

  • Oops, I’m glad it worked out! =]

Browser other questions tagged

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