Ajax returning HTML together with Json

Asked

Viewed 741 times

1

Hello,

I am trying to fill in input data with the result of a database search using as a filter what has been typed before. ex: User enters client code and when the focus of the input, all the following fields are already filled in (name, phone, address)

I made the function below using Jquery to return the search result made in PHP.

      $(document).ready( function() {
       /* Executa a requisição quando o campo CEP perder o foco */
       $('#txtCod').blur(function(){
               /* Configura a requisição AJAX */
               $.ajax({
                    url : 'busca_cliente.php', /* URL que será chamada */ 
                    type : 'POST',  
                    data: 'cod=' + $('#txtCod').val(), /* dado que será enviado via POST */
                    dataType: 'json', /* Tipo de transmissão */
                    complete: function(resposta){
                        //o problema começa aqui !!!
                        $('#txtNome').val(resposta.nome);
                        //console.log(resposta);
                    }
               });   
       return false;    
       })
    });

My problem is that in addition to returning the JSON from what I need, the code is returning an HTML snippet knows God from where, following what is returned

 "<form style=display: inline; margin: 0px; padding: 0px; name=imprimecupom method=post target="_blank">
     <input type=hidden name=op>
     <input type=hidden name="pessoa">
     <input type=hidden name="tipo">
     <input type=hidden name="valorbruto">
     <input type=hidden name="horario">

  </form>


   {"cod_medico":"42","nome":"Guilherme","matricula":"122344","guia":"1","chave":"","senha":"","email":"","sexo":"","cidade":"","estado":"","contato":null,"cpf":"","espec":"","telefone":"","cep":"","endereco":"","cod_operadora":null}"

how to make it return only the JSON, and if there is no way, how to ignore the HTML and only use the JSON of the answer given by Ajax, because, with this extra HTML, I cannot access the JSON to fill in the inputs.

Thank you all;

EDIT

Follow customer search code, as simple as it may be

$cod = $_POST['cod'];
$sql   = "SELECT * FROM clientes WHERE cod_cliente = '{$cod}'";
$res   = mysql_query($sql, $db); 
$linha = mysql_fetch_assoc($res);
echo json_encode($linha);
  • Also enter your page code busca_cliente.php

  • includes @Rafaelacioly here

  • This is all the content of the page busca_cliente.php ?

  • So, apart from opening and closing php tag (I was told that closing can disturb too, I need to test) I make a include in a php security structure (where I also create the connection to the bank)

1 answer

0


The Error was in the database configuration file where there was a lost echo that returned HTML.

Browser other questions tagged

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