Fields filled with zip code in CakePHP 2.x


I'm trying to autocomplete fields in CakePHP from a zip code, I'm adapting the code found on this site:


I used the following site as an example to know how to configure ajax requests for the Framework:


Here is my code:


class ContatoController extends AppController {
    public $components = array('RequestHandler');

    public $uses = array();

    public function beforeRender()
        if ($this->request->is('ajax')) {
            $this->layout = "ajax";

    public function consulta_cep() {
            $reg = simplexml_load_file("" . $cep);

            $dados = $reg->sucesso($this->request->data['resultado']);
            $dados = $reg->rua($this->request->data['tipo_logradouro' . ' ' . 'logradouro']);
            $dados = $reg->bairro($this->request->data['bairro']);
            $dados = $reg->cidade($this->request->data['cidade']);
            $dados = $reg->estado($this->request->data['uf']);

            echo json_encode($dados);


base_url = 
$(document).ready( function() {
    /* Executa a requisição quando o campo CEP perder o foco */
       /* Configura a requisição AJAX */
            url : 'consulta_cep()', /* URL que será chamada */ 
            type : 'POST', /* Tipo da requisição */ 
            data: 'cep=' + $('#cep').val(), /* dado que será enviado via POST */
            dataType: 'json', /* Tipo de transmissão */
            success: function(data){
                if(data.sucesso == 1){

    return false;    

        echo $this->Form->create('Contato');
    <? php
        echo $this->Form->input('cep');
        echo $this->Form->input('rua');
        echo $this->Form->input('numero');
        echo $this->Form->input('bairro');
        echo $this->Form->input('cidade');
        echo $this->Form->input('estado');



I have some doubts:

  • In the test.ctp url url, what should I put, since I want to call the query_cep function found in ContactController

  • The way I'm doing in the controller to play the data that returns in the $ reg variable for the $ data variable is correct, because on the site I used as an example it is converting to String before assigning the values to the variable $ data?

  • I would like your help because I have not found any examples on the internet for CakePHP to use fill in the data from the CEP and I am trying to help the community with the knowledge I have in the Framework so that they can use a basic functionality , but that helps a lot the developers in their projects.

    Thank you

    asked by anonymous 01.02.2015 / 22:16

    0 answers