Problems in the use of PDO

Asked

Viewed 81 times

2

I used to use Mysqli, but now I started using PDO. I’m having a little trouble at the beginning.

I made the code below, only when I use the parole and it enters the else, something is not returned for the return of AJAX. I give a console.log, on the return of AJAX and nothing comes out.

The echo exits in the PHP file, but is not returned.

Could you help me and tell me where I might be going wrong ?

Code:

function pesquisarDetalhesClientes(dados, cod_line, depart_line) {

  $.ajax({
    type: "POST",
    data: {
      botao: dados,
      cod: cod_line,
      depart_ativ: depart_line
    },
    url: "../banco/banco-vision/pagina-controle-de-tarefas/interface-consulta-comentarios-cliente.php",
    cache: false,
    async: false

  }).done(function(data) {
    console.log(data);
    let detalhes = "";

    //Aqui abaixo, preenchemos as divs com os dados vindo da consulta ao arquivo php do AJAX]
    if (data != "naotemresponsavelnaempresa") {
      if (data.detalhes_cliente == null) {
        info = "Não Possui Observações";
        detalhes = "<p>" + info + "</p>";
      } else {
        detalhes = "<p>" + data.detalhes_cliente + "</p>";
      }
    } else {
      //$("#enviar-modal-observacoes-cliente").prop('disabled',true);       
      alert("Sem responsavel");
    }




    //Função para preencher a <div> com os <p> e manter o scroll embaixo
    /*
    $("#espaco-dialogo-atividades").html(detalhes).promise().then(function(){
        $("#espaco-dialogo-atividades").animate({ scrollTop: $("#espaco-dialogo-atividades").prop("scrollHeight") }, 0);
    });
    */

    $("#espaco-dialogo-atividades-cliente").html(detalhes);

  }).fail(function() {

  }).always(function() {

  });
}
<?php

        header("Content-type: application/json; charset=utf-8");

        // CONEXAO
        session_start();
        $banco = $_SESSION['banco'];
        $bancodedados = "mysql:host=localhost;dbname=$banco";
        $usuario_banco = 'jcasiste_marco';
        $senha = 'Arg@tsi@123';

        //CONSULTA NO BANCO QUE PREENCHE A ÁREA DE DETALHE E FEEDBACK NA PARTE DE BAIXO DA TELA INTERFACE.PHP
        date_default_timezone_set('America/Sao_Paulo');

        if(is_string($_SESSION["nome"]))
        {
            $usuario = $_SESSION["nome"];           
        }
        else
        {
            die("A SESSION[nome] não tem caracter String");
            exit;           
        }   

        try
        {

        $conexao = new PDO($bancodedados,$usuario_banco,$senha,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

        //$usuario = $_SESSION["nome"];
        $codigo_detalhes = filter_input(INPUT_POST, 'botao', FILTER_SANITIZE_NUMBER_INT);
        $cod_detalhes = filter_input(INPUT_POST, 'cod', FILTER_SANITIZE_NUMBER_INT);
        $departamento_detalhes = filter_input(INPUT_POST, 'depart_ativ', FILTER_SANITIZE_STRING);


        //COMENTAR ISSO AQUI
        $query = "SELECT * FROM tbl_usuarios_connect WHERE COD = ? and departamento = ?";

        $stmt = $conexao->prepare($query);
        $stmt->bindValue(1,$cod_detalhes);
        $stmt->bindValue(2,$departamento_detalhes);
        $stmt->execute();

        $count_responsaveis_no_cliente = $stmt->rowCount();

        //$result = $stmt->fetch(PDO::FETCH_ASSOC); 

            if($count_responsaveis_no_cliente > 0)
            {           
                $query = "SELECT detalhes_cliente FROM tbl_atividades WHERE codigo = ?";

                $stmt = $conexao->prepare($query);
                $stmt->bindValue(1,$codigo_detalhes);
                $stmt->execute();
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                echo json_encode($result);              
            }
            else
            {
                echo "naotemresponsavelnaempresa";              
            }   
        }
        catch(PDOException $e)
        {
            //Verificando o erro ocorrido
            echo "Erro: ".$e->getCode()." Mensagem: ".$e->getMessage();         
        }                               

?>
  • 1

    Ever thought about returning a valid JSON instead of the string "naotemresponsavelnaempresa"? And see if by chance the function is not being executed fail in your JS. You have not treated this function, so if it is executed you will not know.

  • You have a problem with that ? And what would a valid sjon be ?

  • If JS expects a JSON and you do not send one it will execute the fail instead of done.

  • But the JS really expects a JSON ?

  • 1

    Yes, you said in PHP that you will be sending a JSON when setting the header Content-type: application/json. JS will see that it is a JSON and will attempt to treat the body of the answer as such, making an error because it is not a valid JSON.

  • Follow the tips of Master Anderson, because they can be these same mistakes, to see what can be happening, puts a .fail(function(a,b){console.log(a);console.log(b);} that can help

  • I will follow the tips yes.

  • This was exactly what was happening, @Andersoncarloswoss . So I took String and started returning a JSON. I was actually entering FAIL. Thanks for the help, brother. I’ll update the question and show you how the code looked. If you want to create an answer, I accept for you.

  • @Petherson Don’t edit the question just to add the solution. If it’s solution it should be in the answers.

Show 4 more comments

2 answers

3


In PHP you are sending the following header in the HTTP response:

header("Content-type: application/json; charset=utf-8");

This will make jQuery understand that the answer is a JSON and will attempt to analyze the body of the response as such. The problem is that in PHP the error messages are string raw, like plain text.

die("A SESSION[nome] não tem caracter String");
echo "naotemresponsavelnaempresa";
echo "Erro: ".$e->getCode()." Mensagem: ".$e->getMessage();

If any of these three lines are executed your HTTP response will be something like:

HTTP/1.1 200 OK
Content-Type: application/json

naotemresponsavelnaempresa

This will cause Javascript, when jQuery tries to analyze the body of the answer, to JSON.parse("naotemresponsavelnaempresa").

const resultado = JSON.parse("naotemresponsavelnaempresa")

console.log(resultado)

It will give error because the value is not a valid JSON. So, when giving error, instead of running the callback done the fail.

It’s up to you to decide whether to change PHP forever to return a valid JSON or whether to change the JS to also handle errors.

2

After following Anderson’s lead, I did the code the right way. It goes down like it was:

function pesquisarDetalhesClientes(dados, cod_line, depart_line) {

  $.ajax({
    type: "POST",
    data: {
      botao: dados,
      cod: cod_line,
      depart_ativ: depart_line
    },
    url: "../banco/banco-vision/pagina-controle-de-tarefas/interface-consulta-comentarios-cliente.php",
    cache: false



  }).done(function(data) {

    let detalhes = "";

    //Aqui abaixo, preenchemos as divs com os dados vindo da consulta ao arquivo php do AJAX]

    if (data.count != 0) {
      if (data.preencher.detalhes_cliente == null) {

        info = "Não Possui Observações";
        detalhes = "<p>" + info + "</p>";
      } else {
        detalhes = "<p>" + data.preencher.detalhes_cliente + "</p>";
      }
    } else {

      $("#enviar-modal-observacoes-cliente").prop("disabled", true);
      $("#div-botao-enviar-mensagem-cliente").prepend("<span class='text-danger font-weight-bold'>Cliente não possui correspondente no departamento <span class='text-dark'>" + data.preencher.departamento + "</span> cadastrado no Connect!</span>");
    }

    $("#espaco-dialogo-atividades-cliente").html(detalhes);

  }).fail(function() {
    alert("Erro na consulta: Verifique com o T.I");
  }).always(function() {

  });
}
<?php
				
		header("Content-type: application/json; charset=utf-8");
								
		// CONEXAO
		session_start();
		$banco = $_SESSION['banco'];
		$bancodedados = "mysql:host=localhost;dbname=$banco";
		$usuario_banco = 'jcasiste_marco';
		$senha = 'Arg@tsi@123';
						
		//CONSULTA NO BANCO QUE PREENCHE A ÁREA DE DETALHE E FEEDBACK NA PARTE DE BAIXO DA TELA INTERFACE.PHP
		date_default_timezone_set('America/Sao_Paulo');
				
		   		
		try
		{
			
		$conexao = new PDO($bancodedados,$usuario_banco,$senha,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
			
		//$usuario = $_SESSION["nome"];
		$codigo_detalhes = filter_input(INPUT_POST, 'botao', FILTER_SANITIZE_NUMBER_INT);
		$cod_detalhes = filter_input(INPUT_POST, 'cod', FILTER_SANITIZE_NUMBER_INT);
		$departamento_detalhes = filter_input(INPUT_POST, 'depart_ativ', FILTER_SANITIZE_STRING);
					
		
		//COMENTAR ISSO AQUI
		
		$query = "SELECT * FROM tbl_usuarios_connect WHERE COD = :cod_detalhes and departamento = :departamento_detalhes";
		$stmt = $conexao->prepare($query);
		$stmt->bindValue(':cod_detalhes',$cod_detalhes);
		$stmt->bindValue(':departamento_detalhes',$departamento_detalhes);
		$stmt->execute();
		
		$count_responsaveis_no_cliente = $stmt->rowCount();
			
		$query = "SELECT detalhes_cliente, departamento FROM tbl_atividades WHERE codigo = :codigo";
		
		$stmt = $conexao->prepare($query);
		$stmt->bindValue(":codigo",$codigo_detalhes);
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		
			
		$json_resultado = array(
			'preencher' => $result,
			'count' => $count_responsaveis_no_cliente				
		);
		
		echo json_encode($json_resultado);			
		
		}
		catch(PDOException $e)
		{
			//Verificando o erro ocorrido
			echo "Erro: ".$e->getCode()." Mensagem: ".$e->getMessage();			
		}								
				
?>

Browser other questions tagged

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