I have a popup that does the geolocation of the client and generates a cookie, which will be used for various purposes in the site.
Everything is working, the only thing I can not understand is that if I put it to load the site, the script works and later.
In the end, I can retrieve the values in PHP.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>SB Admin 2 - Bootstrap Admin Theme</title>
<script type="text/javascript" src="https://www.akiachei.com/js/jquery.min.js"></script><scripttype='text/javascript'src='https://maps.googleapis.com/maps/api/js?key=AIzaSyDh8ey5aysev9_03haI8BmrNhHAic9xX80&libraries=places'></script><scripttype="text/javascript" src="js/jquery-cookie-master/src/jquery.cookie.js"></script>
<script type="text/javascript">
$().ready(function($) {
$(".teste").click(function(){
jQuery(document).ready(function($){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var adress = position.coords.latitude + "," + position.coords.longitude;
var urlToGet = 'https://maps.google.com/maps/api/geocode/json?address=' + adress + '&sensor=false';
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE ) {
if (ajax.status == 200) {
//console.log(ajax.responseText);
var enderecos = JSON.parse(ajax.responseText);
var cidade = enderecos['results'][0]['address_components'][3]['long_name'];
var estado = enderecos['results'][0]['address_components'][5]['short_name'];
var cidade_estado = cidade + " - " + estado;
$.cookie('cookie_cidade_estado', cidade_estado, { expires: 1 });
alert(cidade_estado);
}
}
}
ajax.open('GET', urlToGet, true);
ajax.send();
});
} else {
//document.getElementById('google_canvas').innerHTML = 'No Geolocation Support.';
swal({
title: "Oops...",
text: "A geolocalização não é suportada pelo seu navegador",
type: "error",
confirmButtonColor: "#00bae1"
});
}
var cookie_akiachei = $.cookie('cookie_cidade_estado');
if (cookie_akiachei === undefined || cookie_akiachei === null) {
var cookie_akiachei_chk = '';
var cidade_pre = '';
var cidade_pos = '';
}else{
var cookie_akiachei_chk = cookie_akiachei;
var arr = cookie_akiachei_chk.split(' - ');
var cidade_pre = arr[0];
var cidade_pos = arr[1];
}
});
});
});
</script>
</head>
<body>
<div id="google_canvas"></div>
<?php
echo $cookie_akiachei_php = "<script type=\"text/javascript\" >document.write(cidade_pos)</script>";
?>
<a href="#" class="teste">teste</a>
</body>
</html>
When I do this with the Jquery click event, I can not retrieve the values in PHP.