Get the input value on the same page with PHP

Asked

Viewed 850 times

0

td well?

I have a script in PHP that converts the ZIP code to Coordinate and I would like it to convert automatically according 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 the above he transforms the $cep zip into coordinate, but wanted when inserting the cep into the input he already converted and put the latitude and longitude in the corresponding inputs.

These values will be inserted in a mysql table.

Thank you!

  • In that case you’ll have to make one ajax to obtain the data according to the new zip code

  • Sorry, I am beginner ajax would send the input value to php variable?

  • No, ajax will make a request for: http://maps.google.com/maps/api/geocode/json?address=CEP, where ZIP code is the zip code entered in the input, the ajax response will come with the information you need.

  • Or if you do not allow, for a php script, to make this request and return the answer

1 answer

1


Making ajax request to obtain the latitude and longitude of the zip code 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>
<input type="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>

Browser other questions tagged

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