Ajax Address Search with PHP

3

I have a form with the list of clients. When selecting the client, I want it to automatically fill in the address, number, neighborhood and city fields.

I have Ajax, but I do not know how to work out the return of it.

var id = $('#cliente').val();

$.ajax(
    {
        url:"ajax/endereco/" + id,
        success:function(result) {
            $('[name="servicos[0].endereco"]').val(result.endereco);
            $('[name="servicos[0].numero"]').val(result.numero);
            $('[name="servicos[0].bairro"]').val(result.bairro);
            $('[name="servicos[0].cidade"]').val(result.cidade);
        }
    }
);

I would like to know how to be able to import the data that comes from this address ... or how to display the data, what would his PHP be like? Thanks guys.

    
asked by anonymous 09.06.2015 / 19:22

1 answer

2

Your ajax is sure to just add some things

$.ajax({
    type: 'GET',
    url: 'url:"ajax/endereco/id/" + id,',
    async: false,
    success:function(d){
        result = JSON.parse(d);
        $('[name="servicos[0].endereco"]').val(result.endereco);
        $('[name="servicos[0].numero"]').val(result.numero);
        $('[name="servicos[0].bairro"]').val(result.bairro);
        $('[name="servicos[0].cidade"]').val(result.cidade);
    }
});

I usually use async: false in this type of request to make sure that it will only try to put the information in the fields after it is returned.

And PHP looks like this

public function suaFuncao(){
    $id = $this->params()->fromRoute('id', 0);
    $conect = "parametros de conexão com o banco ";
    $sql = "SELECT * FROM tabela WHERE id = $id";
    $result = pg_fetch_all(pg_query($conect, $sql));
    echo json_encode($result); exit;

}

PHP is very simple, you just get the id that is coming by parameter and uses it in your query , the result you return giving json_encode

    
09.06.2015 / 19:48