Geolocation is working in local but doesn't on remote server - javascript

I uploaded the web app that I'm working on to a remote server.
Everything is working good, except for the geolocation. I can't understand what is the problem, beacuse I didn't receive any error message.
this the HTML code where geolocation is involved.
<tr>
<td>Ti trovi qui: <span id="location"></span></td>
</tr>
</table>
<input type="hidden" id="latitude" name="latitude">
<input type="hidden" id="longitude" name="longitude">
</form>
These are the scripts that I use: (i'm not very prepared with javascript and jQuery)
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
jQuery.ajax({
type:'POST',
url:'getLocation.php',
data:'latitude='+latitude+'&longitude='+longitude,
success:function(msg){
if(msg){
jQuery("#location").html(msg);
}else{
jQuery("#location").html('Not Available');
}
}
});
}
function getUserCoordinates(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.getElementById('latitude').value=latitude
document.getElementById('longitude').value=longitude
}
jQuery(document).ready(function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getUserCoordinates);
navigator.geolocation.getCurrentPosition(showLocation);
} else {
jQuery('#location').html('Geolocation is not supported by this browser.');
}
});
This is getLocation.php file (but I don't think it's the problem):
<?php
require_once 'metodi.php';
sec_session_start();
if(login_check() == true){
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
$_SESSION['latitude'] = $_POST['latitude'];
$_SESSION['longitude'] = $_POST['longitude'];
//Send request and receive json data by latitude and longitude
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
$json = #file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if($status=="OK"){
//Get address from json data
$location = $data->results[0]->formatted_address;
}else{
$location = '';
}
//Print address
echo $location;
}
} else {
echo "Non sei autorizzato a visualizzare questa pagina. Effettua il login.";
}
?>
Then I grab the value of hidden inputs in another php file.

If your website is running in https, you also need to change this
http://maps.googleapis.com/maps/api/geocode/json?latlng=
to this
https://maps.googleapis.com/maps/api/geocode/json?latlng=

getCurrentPosition() is asynchronous. When you call it twice there is no guarantee that the first call will complete before the second one does. It also makes no sense to call it twice back to back
Also it relies on third party service to return the data
Only call it once, and pass the response values to both of your functions inside one callback
Change
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getUserCoordinates);
navigator.geolocation.getCurrentPosition(showLocation);
} else {
To
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
getUserCoordinates(position);
showLocation(position);
});
} else {
Also check that you haven't disabled geolocation in your browser for the the remote domain. Add some console logging to see what is and isn't running within the code

Related

Geolocation script not returning value

I am trying to use Javascript for finding user location but it is not giving me any value, my code is below
<script>
window.onload = function() {
var startPos;
var geoSuccess = function(position) {
startPos = position;
document.getElementById('startLat').innerHTML = startPos.coords.latitude;
document.getElementById('startLon').innerHTML = startPos.coords.longitude;
};
navigator.geolocation.getCurrentPosition(geoSuccess);
};
</script>
<?php echo "<script> getCurrentPosition('startLat') </script>"; ?>
The HTML5 Geolocation API allows you to get a user's Latitude/Longitude with some JavaScript (if the browser is compatible, and if the user allows access to his/her location).
You can then reverse-geocode the location to get an address, there are several free reverse-geocoding services other than Google's API.
you can also check out this link How to get geographical location of an IP address in PHP for more understanding
Example:
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
If you have elements with id's "startLat" and "startLon" in your HTML, it'll work
Just add in HTML:
<p id="startLat"></p>
<p id="startLon"></p>
You can delete this line, actually:
<?php echo "<script> getCurrentPosition('startLat') </script>"; ?>
To use Latitude/Longitude in your PHP you can send the values via JS
In HTML
<script>
function sendData(value) {
var request = new XMLHttpRequest();
request.open('post', 'DESTINATION.PHP', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('data=' + value);
}
</script>
Or as a hidden form input
and access in PHP
if(isset($_POST['data'])){
$data = $_POST['data'];
// Do stuff...
}

How to call Javascript API to Get IP Address in PHP Function?

I have a problem while calling javasript function in php. I found this script in : How to get client's IP address using javascript only?
<html>
<body>
<h1> Demo retrieving Client IP using WebRTC </h1>
<script type="text/javascript">
function findIP(onNewIP) { // onNewIp - your listener function for new IPs
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
var pc = new myPeerConnection({iceServers: []}),
noop = function() {},
localIPs = {},
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
key;
function ipIterate(ip) {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
}
pc.createDataChannel(""); //create a bogus data channel
pc.createOffer(function(sdp) {
sdp.sdp.split('\n').forEach(function(line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(ipIterate);
});
pc.setLocalDescription(sdp, noop, noop);
}, noop); // create offer and set local description
pc.onicecandidate = function(ice) { //listen for candidate events
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
};
}
var ul = document.createElement('ul');
ul.textContent = 'Your IPs are: '
document.body.appendChild(ul);
function addIP(ip) {
console.log('got ip: ', ip);
var li = document.createElement('li');
li.textContent = ip;
ul.appendChild(li);
}
findIP(addIP);
</script>
<?php echo "<script>addIP(ip);</script>"; ?>
</body>
</html>
Why it's all suddenly gone while i add this script :
<?php echo "<script>addIP(ip);</script>"; ?>
Is there anything wrong with my code ? Please Help
It looks like you're calling the addIP() function with a variable called ip that does not exist. I'm assuming you want to substitute that with the user's IP. To do this you would pass the IP address from PHP to Javascript with the following:
<?php echo '<script>addIP("' . $_SERVER['REMOTE_ADDR'] . '")</script>'; ?>
If you're testing locally it might output something like:
<script>addIP("::1")</script>
<script>addIP("127.0.0.1")</script>
<script>addIP("192.168.0.1")</script>
REMOTE_ADDR is not always reliable as it's sometimes the address of a proxy server the user is behind.
change from server call <?php echo "<script>addIP(ip);</script>"; ?> to client call <script type="text/javascript"> addIP(ip); </script>
(Just in case: your html file needs to use .php as extension.)
Try changing to:
<script type="text/javascript"> addIP(<?php echo $ip; ?>); </script>
On a side note: Something like this method of php in html will work fine but using a template engine would remove php code from display logic. Something like phpTal or one of the many others would be good to use. If you are only doing it for one value then don't bother with templating. but if you are dynamically creating html by using html in you php or php in your html then a template langue is what I would recommended.

Ajax call not working properly when used with Recaptcha

I am using PHP and AJAX together in my website to fetch data from a JSON URL and to display it on the webpage. When I use it without implementing recaptcha, it works fine but when I integrate Google's Recaptcha, the results get displayed only when the captcha puzzle is solved twice everytime. I am not sure where the bug actually lies and I even tried to implement a custom captcha and in that case also it is the same. Here is the code with recaptcha,
Captcha and Ajax code snippet :
<?php
if ($resp != null && $resp->success): ?>
echo"hi";
<script>
$(document).ready(function(){
$("#submit").click(function(){
$.post("retrieve_train_between_stations.php", $("#get_train_running").serialize(), function(response) {
$("#success").html(response);
});
return false;
});
});
</script>
<?php
else:
echo "Failed";
?>
Full code :
http://pastebin.com/UynEiYng
This part should be moved to retrieve_train_between_stations.php.
require_once "recaptchalib.php";
// your secret key
$secret = "My secret key";
// check secret key
$reCaptcha = new ReCaptcha($secret);
$resp = false;
if (isset($_POST["g-recaptcha-response"])) {
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
if ($resp) {
//display the record
} else {
echo 'Recaptcha can not be verified.';
}
The if/else should be removed and prevent the default event for the script
<script>
$(document).ready(function(){
$("#submit").click(function(event){
event.preventDefault();
$.post("retrieve_train_between_stations.php", $("#get_train_running").serialize(), function(response) {
$("#success").html(response);
});
return false;
});
});
</script>

How to send json_encode data with HTML5 SSE

I have a script that fires an SSE event for fetching json encoded data from online.php.
On googling, I found ways to send JSON data with sse, by introducing line-breaks.
What I am looking for is how to send JSON over SSE when the JSON array is created using PHP's json_encode() function.
I have written the following lines of code, but could anybody help me with where to add the "data: \n\n" required for SSE?
<script>
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource("online.php");
source.onmessage=function(event)
{
var data=JSON.parse(event.data);
$("#new_message").html("Inbox"+data['total']);
};
}
else
{
$("#new_message").html("HTML5 not supported");
}
</script>
online.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$data["total"]="hello";
echo json_encode($data);
ob_flush();
flush();
?>
You need to send it in EventStream format, which in this case is just prepending it with data:
echo 'data: ' . json_encode($data) . "\n\n";
You can encode the $data array like Ryan said:
echo 'data: ' . json_encode($data) . "\n\n";
Then, client side, event.data will be viewed as a string, which you can then easily parse to json using query's jQuery.parseJSON(). so your client-side code will look something like this:
// Check if the browser supports SSE
if (typeof (EventSource) !== "undefined") {
var source = new EventSource("script.php");
// Handle evetns
source.onmessage = function(event) {
// parse the data that has an object as a string
var msg = $.parseJSON(event.data);
// Do awesome code with the values inside msg
};
} else {
alert("Sorry, your browser doesn't support this awesome feature!");
}
Source: http://api.jquery.com/jquery.parsejson/
Your script will only show output once as it needs to have some kind of a loop to keep running (conditionally of course or you'll have millions of instances running!!).
I've chopped up an implementation I wrote earlier today which demonstrates this and also added some additional javascript/jquery to help manage the streams better. The below will also work on a single threaded PHP installation like Xampp (for local development)
Notes on Xampp: As the PHP script is in a loop and doesn't terminate immediately it will stop a new php or agax script from running. If you're using ajax as well to call PHP call stream_close() in the beforesend and stream_open() in the success callbacks.
The below is untested but it's mainly grabbed from working code so it should be fine.
<?
//stream.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
stream();
function stream(){
$data = array();
//collect data from database or wherever to stream to browser
//example data
$data[0]["name"] = 'Bob';
$data[0]["total"] = rand(0,100);
$data[0]["name"] = 'Jane';
$data[0]["total"] = rand(0,100);
//maybe there is no new data so just send one new line
//this is required to check if the connection is still alive
if(!empty($data)){
echo "\n";
}else{ //Otherwise json encode the data for output
echo 'data: '.json_encode($data)."\n\n";
}
flush(); //Flush the result to the browser
sleep(1); //Wait a second (or what ever you like)
//If the browser is still connected
if(!connection_aborted() && connection_status()==0){
stream(); //recurse the function
}
}
?>
<script>
var webstream = false;
function stream_open(){
stream_close(); //Close the stream it (in case we got here weirdly)
if(!!window.EventSource){ //Test compatibility
webstream = new EventSource('./stream.php');
console.log("Stream Opened"); //Log event for testing
webstream.addEventListener('message', function(e){
var data = JSON.parse(e.data); //Parse the json into an object
process_stream(data);
},false);
//Cleanup after navigating away (optional)
$(window).bind('beforeunload', function(){
webstream.onclose = function(){}; //delete onclose (optional)
webstream.close(); //Close the stream
});
}
}
function stream_close(){
if(typeof(webstream)=="object"){
webstream.close();
webstream = false;
console.log("Stream Closed"); //Log event for testing
}
}
function process_stream(data){
//do something with the new data from the stream, e.g. log in console
console.log(data);
}
//Optional:
//Toggle stream on blur/focus
//Good if the user opens multiple windows or Xampp?
$(window).on("blur focus", function(e) {
//get the last blur/focus event type
var prevType = $(this).data("prevType") || null;
if (prevType != e.type){
console.log(e.type); //Log event for testing (focus/blur)
switch (e.type){
case "blur":
stream_close(); //Close stream on blur
break;
case "focus":
stream_open(); //Open stream on focus
break;
}
}
//Store the last event type to data
$(this).data("prevType", e.type);
});
// Optional:
// Using idletimer plugin to close the stream in times of inactivity
// https://github.com/thorst/jquery-idletimer/blob/master/src/idle-timer.js
$(document).on("idle.idleTimer", function (){
stream_close();
});
$(document).on("active.idleTimer", function (){
stream_open();
});
$(document).idleTimer({timeout:5000}); //5 second idle timer
</script>

Getting users city and country info using Google GeoApi

I am using this code to get users full address info
function getGeo() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (a) {
$("#geoLoc").html("Determing your location..");
$.post("https://mysite.com/getloc.php?l=" + a.coords.latitude + "," + a.coords.longitude, function (b) {
var c = jsonParse(b);
geo_adres = c.results[0].formatted_address;
latitude = a.coords.latitude;
longitude = a.coords.longitude;
$("#geoLoc").html(c.results[0].formatted_address);
$("#geoLoc").show("slow")
})
}, function (a) {
alert(geolocationErrorMessages[a.code])
}, {
enableHighAccuracy: true,
maximumAge: 12e4
});
return false
} else {
alert("Your browser doesn't support geo-location feature...")
}
}
EDIT:
getloc.php contains this codes (c var in javascript)
$data = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?latlng=". $_GET['l'] ."&sensor=false");
print $data;
Actually all i want is to get users city and country info like that city, country
How should i change this one c.results[0].formatted_address to achieve that ?
Try this working php code, i hope this is going to help you a lot :) and let mew know in case of any query --
<?php
$data = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false");
$jsonnew =json_decode($data,true);
echo "<pre>";
print_r($jsonnew['results'][7]['address_components'][2]['long_name']);
echo "<pre>";
print_r($jsonnew['results'][6]['address_components'][2]['long_name']);
You shouldn't need your getloc PHP script. The Maps Javascript API includes a Geocoder class.

Categories