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:
ContactsController
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() {
if($this->request->is('post')){
$reg = simplexml_load_file("http://cep.republicavirtual.com.br/web_cep.php?formato=xml&cep=" . $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);
}
}
test.ctp
base_url =
$(document).ready( function() {
/* Executa a requisição quando o campo CEP perder o foco */
$('#cep').blur(function(){
/* Configura a requisição AJAX */
$.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){
$('#rua').val(data.rua);
$('#bairro').val(data.bairro);
$('#cidade').val(data.cidade);
$('#estado').val(data.estado);
$('#numero').focus();
}
}
});
return false;
})
});
<fieldset>
<?php
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');
?>
</fieldset>
routes.php
Router::parseExtensions('json');
I have some doubts:
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