Return JSON to PHP

2

I'm doing a registration system, where the zip code search should appear as soon as the field changes. But the AJAX return is not working. How to return from JSON to PHP? PS: CEP's search is offline

<script type="text/javascript">
jQuery(function($){
   $("#cep").change(function(){
      var cep = $(this).val();
      if( cep.length <= 0 ) return;
      $.getJSON('cep.ajax.php',{cep: $(this).val(), ajax: 'true'}, function(result) {
      alert(JSON.stringify(result));
            $("input#cep").val( result.cep );
            $("input#estado").val( result.uf );
            $("input#cidade").val( result.cidade );
            $("input#bairro").val( result.bairro );
            $("input#endereco").val( result.rua );
            $("input#estado").val( result.uf );
               });
            });
         });

</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script><label>CEP:</label><inputtype="text" name="cep" id="cep" /><br />
<label>Bairro:</label><input type="text" name="bairro" id="bairro" /><br />
<label>Endereço:</label><input type="text" name="endereco" id="endereco" /><br />
<label>Número:</label><input type="text" name="numero" id="numero" /><br />
<label>Complemento:</label><input type="text" name="complemento" id="complemento" /><br />
<label>Cidade:</label><input type="text" name="cidade" id="cidade" /><br />
<label>Estado:</label><input type="text" name="estado" id="estado" /><br />


//arquivo cep.ajax.php
<?php

	$cep = mysqli_real_escape_string($concep, $_REQUEST['cep'] );
    $cep5 = substr($cep,0,5);


    //define tabela
	$sql = "SELECT * FROM cep_log_index WHERE cep5='$cep5'";
	$res = mysqli_query($concep, $sql );
	while ( $row = mysqli_fetch_assoc( $res ) ) {
		    $uf	= $row['uf'];
	}
	
	//busca cep
	$sql2 = "SELECT * FROM $uf WHERE cep='$cep'";
	$res2 = mysqli_query($concep, $sql2 );
	while ( $row = mysqli_fetch_assoc( $res2 ) ) {
		    $tipo = $row['tp_logradouro'];
            $rua  =  $row['logradouro'];
            $bairro =  $row['bairro'];
            $cidade =  $row['cidade'];
            $cep = $row['cep'];
	};

$endereco = array("tipo"=>$tipo, "rua"=>$rua, "bairro"=>$bairro, "cidade"=>$cidade, "cep"=>$cep, "uf"=>$uf);

echo json_encode($endereco);

?>
    
asked by anonymous 28.09.2015 / 22:52

2 answers

3

I discovered the problem. It did not echo because of the accent. It was just put the encoding as below in the file cep.ajax.php and the problem was solved!

$cidade = (utf8_encode($row['cidade']));
    
01.10.2015 / 19:46
0

Adds header Content-Type

header('Content-Type: application/json');
echo json_encode($endereco);
    
28.09.2015 / 23:12