Ajax Address Search with PHP

Asked

Viewed 162 times

3

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

I have Ajax, but I don’t know how to elaborate on his return.

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 import the data that comes from this address... or how to display the data, what would PHP look like? Thank you guys.

  • What gives you success:function(result) { console.log(result); ?

  • It doesn’t print anything. But if I give an Alert(id), it will print the ID that I pass to it... what I am not knowing how to develop, is PHP, which displays these results...

  • Already have something in PHP? how is the query you are doing?

  • No... actually, I’ve assembled the Ajax module now... to see if I can get to this result... But I have no idea how to put in the codeigniter...

1 answer

2


Your ajax ta right just need to add a few 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);
    }
});

Normally I use async: false in this type of request to make sure that you will only try to place the information in the fields after they are 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 only take the id that is coming by parameter and use it in your query, the result you return giving a json_encode

  • I couldn’t. nor install the ajax module... I will think more about it

Browser other questions tagged

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