Get input value on same page with PHP [duplicate]

0

All right?

I have a PHP script that converts the ZIP code into a Coordinate and would like it to automatically convert to the value of an input.

<input type="text" value="" id="cep" >
<input type="text" value="" id="latitude">
<input type="text" value="" id="longitude">
<?php
    $cep = '01311-100';
    $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$cep.'&sensor=false');
    $output= json_decode($geocode);
    $lat = $output->results[0]->geometry->location->lat;
    $long = $output->results[0]->geometry->location->lng;
    echo $lat;
    echo $long;
    ?>

In this above it transforms the cep of $ cep into coordinate, but wanted that when inserting the cep in the input it already converted and put the latitude and longitude in the corresponding inputs.

These values will be inserted into a mysql table.

Thank you!

    
asked by anonymous 02.06.2017 / 21:16

1 answer

1

Applying ajax to get ZIP code latitude and longitude dynamically:

$('#cep').keyup(function() { // Dispara a função quando um caracter é digitado
  if(this.value.length > 7) { // Checa se o campo cep tem mais de 7 caracteres
    
    // Requisição ajax.
    var request = $.ajax({
      url: "https://maps.google.com/maps/api/geocode/json?address=21331009",
      method: "GET",
      dataType: 'json'
    });
    
    // Executa caso tenha sucesso na requisição.
    request.done(function( response ) {
      let location = response.results[0].geometry.location; // Obtém os valores de latitude e longitude
      
      // Muda adiciona os valores nos campos correspondentes
      $('#latitude').val(location.lat);
      $('#longitude').val(location.lng);
    });

    // Executa caso a requisição falhe.
    request.fail(function() {
      alert('Erro');
    });
  } else { // Limpa latitude e longitude caso o cep esteja incompleto
    $('#latitude').val('');
    $('#longitude').val('');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" value="" id="cep" maxlength="8" placeholder="Digite o CEP aqui...">
<input type="text" value="" id="latitude" readonly>
<input type="text" value="" id="longitude" readonly>
    
02.06.2017 / 21:56