Retrieving database data through PHP, based on the Javascript function value - javascript

I am getting a place name to this file using GET. Then I am converting the place name into latitude and longitude.
I want to display some data from the database, based on the latitude and longitude, but I am unable to send the latitude and longitude variables from JS to PHP.
I also tried Ajax, but that also didn't work, because PHP loads before the script. Correct me if I am wrong.
Any kind of help will be appreciated.
<?php
$user_latitude
$user_longitude
$result=$con->query("SELECT *, ( 6371 * acos( cos( radians($user_latitude) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians($user_longitude) ) + sin( radians($user_latitude) ) * sin( radians( lat ) ) ) ) AS distance FROM Location HAVING distance < 100 ORDER BY distance LIMIT 0 , 10");
for($x=0;$x<$result->num_rows;$x++){
$row=$result->fetch_assoc();
echo "<div class='result-data'>";
echo $row["name"];
echo "</div>";
}
?>
<script>
$(function() {
geocoder = new google.maps.Geocoder();
alert($_GET('location'));
var address = $_GET('location');
address=address+',Delhi,India';
alert(address);
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude=results[0].geometry.location.lat();
longituderesults[0].geometry.location.lng();
alert("Latitude: "+results[0].geometry.location.lat()+latitude);
alert("Longitude: "+results[0].geometry.location.lng()+longitude);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
function $_GET(param) {
var vars = {};
window.location.href.replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if (param) {
return vars[param] ? vars[param] : null;
}
return vars;
}
</script>

Going to have to use AJAX to be able to achieve your desired result for this one. Due to the order of operations that need to be executed, I can't see another way around it.
Here's some example code for you, you'll also need to split your code into two files.
file1.php (using jQuery AJAX, hope that's OK)
<?php
if(isset($_GET)){
$location = $_GET['l'];
}
?>
<div id="test"></div>
<script>
$(function() {
geocoder = new google.maps.Geocoder();
alert('<?=$location?>');
var address = '<?=$location?>';
address=address+',Delhi,India';
alert(address);
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude=results[0].geometry.location.lat();
var longitude=results[0].geometry.location.lng();
alert("Latitude: "+results[0].geometry.location.lat()+latitude);//Both of these would be the same?
alert("Longitude: "+results[0].geometry.location.lng()+longitude);
$.ajax (
{
type : "POST",
url : "file2.php",
data :
{
longitude:longitude,
latitude:latitude
},
success : function(result)
{
$('#test').html(result);
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(thrownError);
}
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
</script>
Note you were missing = for you longitude variable declaration.
file2.php (this is the file ajax will request and then pull down the data)
<?php
//connection to your DB here
$user_latitude = $_POST['latitude'];
$user_longitude = $_POST['longitude'];
$result=$con->query("SELECT *, ( 6371 * acos( cos( radians($user_latitude) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians($user_longitude) ) + sin( radians($user_latitude) ) * sin( radians( lat ) ) ) ) AS distance FROM Location HAVING distance < 100 ORDER BY distance LIMIT 0 , 10");
for($x=0;$x<$result->num_rows;$x++){
$row=$result->fetch_assoc();
echo "<div class='result-data'>";
echo $row["name"];
echo "</div>";
}
This way the location name will be loaded with $_GET from the URL (something like mysite.com/file1.php?l=delhi) and passed to JS, AJAX call then made to the php file that requests the data from the DB. Then finally this is displayed in the id=test div.
This should work but there are some security concerns with $_GET you should be aware of. http://www.ultramegasoft.com/blog/2009/08/5-basic-php-security-tips/ Also a ton of information about $_GET on SO. I wouldn't use the above code in production without some tightening. This method with also chain your JS to PHP which is not ideal.

$_GET is a php function, so calling it inside your JavaScript won't work. You need to use something like: http://api.jquery.com/jquery.ajax/ and setup an endpoint on your server to deal with the ajax request.

Related

Pass data from javascript to php in the same page

i want to make a function on my landing page that get the user location and calculate the nearest store and show it on the page.. im using this code to calculate..
var cities = [
["city1", 10, 50, "blah"],
["city2", 40, 60, "blah"],
["city3", 25, 10, "blah"],
];
function NearestCity(latitude, longitude) {
var mindif = 99999;
var closest;
for (index = 0; index < cities.length; ++index) {
var dif = PythagorasEquirectangular(latitude, longitude, cities[index][1], cities[index][2]);
if (dif < mindif) {
closest = index;
mindif = dif;
}
}
alert(cities[closest]);
}
how to pass the result to php and store to db?
To pass the data from the NearestCity function you would typically use ajax - the request can be to the same page or another depending upon your own preference. Below shows how you might send the data to the same page to be used by your PHP code - in this case it doesn't save the info to the database but it could do so very easily.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* read and process ajax post request - available through the "$_POST" array */
/* add to db or whatever */
/*
send response to ajax callback
Here it is just a simple output showing the data that was sent via POST
but should be more meaningful ~ perhaps db results or html content etc
*/
echo implode( PHP_EOL, $_POST );
exit();
}
?>
<!doctype html>
<html>
<head>
<title>Find nearest - send via ajax to same page</title>
<script>
var defaults={
lat:52.628593,
lng:1.296380
};
var cities = [
['Aylsham', 52.794847, 1.252565, 'Aylsham is a historic market town and civil parish on the River Bure in north Norfolk, England'],
['North Walsham', 52.823477, 1.390931, 'North Walsham is a market town and civil parish in Norfolk, England within the North Norfolk district'],
['Dereham', 52.681311, 0.939737, 'Dereham, also known as East Dereham, is a town and civil parish in the English county of Norfolk'],
['Cambridge',52.204548, 0.124404,'Cambridge is a city on the River Cam in eastern England, home to the prestigious University of Cambridge, dating to 1209'],
['Swanton Morley',52.714710, 0.986908,'Swanton Morley is a village and civil parish situated in the English county of Norfolk']
];
function Deg2Rad(deg) {
return deg * Math.PI / 180;
}
function PythagorasEquirectangular(lat1, lon1, lat2, lon2) {
lat1 = Deg2Rad(lat1);
lat2 = Deg2Rad(lat2);
lon1 = Deg2Rad(lon1);
lon2 = Deg2Rad(lon2);
var R = 6371; // km
var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
var y = (lat2 - lat1);
var d = Math.sqrt(x * x + y * y) * R;
return d;
}
function NearestCity( _latitude, _longitude ) {
var mindif = 99999;
var closest;
var tmp=[];
console.info('Find nearest city based upon lat:%s and lng:%s',_latitude, _longitude);
for ( var i=0; i < cities.length; i++ ) {
var _lat=cities[i][1];
var _lng=cities[i][2];
var difference = PythagorasEquirectangular( _latitude, _longitude, _lat, _lng );
if( difference < mindif ) {
closest = i;
mindif = difference;
tmp.push( cities[ i ] );
}
}
/* send request to the same page! */
ajax.call( this, location.href, tmp, cbNearestCity );
}
function ajax( url, params, callback ){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 ){
callback.call( this, this.response );
}
};
var payload=[];
for( var n in params )payload.push( params[n][0]+'='+params[n] );
xhr.open( 'post', url, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.send( payload.join('&') );
}
function cbNearestCity(response){
document.getElementById('results').innerHTML=response;
}
document.addEventListener('DOMContentLoaded',function(e){
if( navigator.geolocation ){
navigator.geolocation.getCurrentPosition( function( pos ){
NearestCity.call( this, pos.coords.latitude, pos.coords.longitude );
});
} else {
NearestCity.call( this, defaults.lat, defaults.lng );
}
},{ capture:false, passive:true } );
</script>
</head>
<body>
<h1>Find nearest city - using geolocation on page load</h1>
<pre id='results'></pre>
</body>
</html>
You can use AJAX for communications between frontend and backend.
Check this MDN guide for AJAX.
Also, you can check this SO question and the many questions tagged ajax to learn more.
So your heading is -
Pass data from javascript to php in the same page
If it would have possible web development has been changed a lot.
Javascript is a client side programming language.
and php is a server side programming language.
You can not pass data to php in the same page without reloading.
you will have to use ajax to pass the data to php but for that you will have to make different php page, not in the same page.
But if you still wants to pass data from javascript to the same page, you will have to reload the page.
- pass data to the hidden field
- by javascript automatically post the form
- page will reload and you will get the result in $_POST in a same page
(but not a good way.)
You need to make and AJAX request to the PHP page.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "abc.php", true);
xhttp.send("mindif="+mindif+"&&closest="+closest);
Add this to the end of your function after you have calculated the value.
Quick reference - Ajax Javascript
after calculate, you can send data via ajax request:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
click here for more detail

walkscore API JSON error

i am trying to get a walkscore from the walkscore API.
i make the ajax request to my php file, i get the response but i kee getting "Unexpected end of JSON input" when i try to alert the walkscore.
This is the PHP (if i test it directly through the URL, it gives me a perfectly json formatted result)
<?
function getWalkScore($lat, $lon, $address) {
$address=urlencode($address);
$url = "http://api.walkscore.com/score?format=json&address=$address";
$url .= "&lat=$lat&lon=$lon&wsapikey=KEY";
$str = #file_get_contents($url);
return $str;
}
$lat = $_GET['lat'];
$lon = $_GET['lon'];
$address = stripslashes($_GET['address']);
$json = getWalkScore($lat,$lon,$address);
echo $json;
?>
and this is my ajax call:
function loadStats() {
var geocoder = new google.maps.Geocoder;
var latlngStr = $("#loadStats").attr("data-latlng").split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
var reverseAddress='';
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
/*** Getting address needed for Walkability API call ***/
reverseAddress = results[1].formatted_address;
//alert (parseFloat(latlngStr[0]));
//alert(parseFloat(latlngStr[1]));
//alert(reverseAddress);
$.ajax({
type:"GET",
url:"scripts/walkscore.php",
data: {"address" : reverseAddress ,
"lat" : parseFloat(latlngStr[0]),
"lng" : parseFloat(latlngStr[1])
},
success: function(response){
var obj = $.parseJSON(response);
alert(obj.walkscore);
}
});
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
//var Lat=$("#loadStats").attr("data-latlng").slice(0, $("#loadStats").attr("data-latlng").indexOf(",")) ;
//var Lng=$("#loadStats").attr("data-latlng").slice($("#loadStats").attr("data-latlng").indexOf(",")+1,$("#loadStats").attr("data-latlng").lenght) ;
}
I don't know what i am doing wrong. this is the JSON i get from the API
{ "status": 1 , "walkscore": 4 , "description": "Car-Dependent" , "updated": "2016-04-04 21:15:44.699150" , "logo_url": "https://cdn.walk.sc/images/api-logo.png" , "more_info_icon": "https://cdn.walk.sc/images/api-more-info.gif" , "more_info_link": "https://www.redfin.com/how-walk-score-works" , "ws_link": "https://www.walkscore.com/score/Acres-homes-Houston-TX-USA/lat=29.852555/lng=-95.447845/?utm_source=cinquedomande.com&utm_medium=ws_api&utm_campaign=ws_api" , "help_link": "https://www.redfin.com/how-walk-score-works" , "snapped_lat": 29.8530 , "snapped_lon": -95.4480 }
I figured it out.
I was stupid enough to pass lng instead of lon to the php script.

Undefined variable when passing javascript variable to PHP with AJAX

I am trying to build a simple mobile app that checks database and gives user the correct venue based on their location. Essentially, I have two files: one with geolocation, JavaScript and AJAX call, and another one with php that checks the database and sends the correct result back. Everything on its own is working perfectly fine, but when I try to send geolocation coordinates to PHP it returns undefined. Why does it not pick up the coordinates (they pop up in a separate window)? How can I fix it?
Here is my geolocation and AJAX code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$( document ).ready(function() {
var latitude;
var longitude;
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
var request = $.ajax({
url: "http://cs11ks.icsnewmedia.net/mobilemedia/ajax.php?latitude=" + latitude + "&longitude=" + longitude,
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#ajax").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
</script>
And here is the bit of PHP that handles these variables:
if (isset($_GET['latitude']) && isset($_GET['longitude'])) {
$latitude = $_GET['latitude'];
$longitude = $_GET['longitude'];
echo "Geolocation seems to work...";
echo $latitude;
echo $longitude;
//continue here
}else{
echo "Hello. I am your geolocation and I am not working.";
}
What I get is "Geolocation seems to work...undefinedundefined"
The Geolocation API is asynchronous, so you have to wait for the result to return
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
url : "http://cs11ks.icsnewmedia.net/mobilemedia/ajax.php",
data : {latitude : latitude, longitude : longitude},
type : "GET",
dataType : "html"
}).done(function(msg) {
$("#ajax").html(msg);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}
remove var in both variable. Those two are not visible outside displayPosition. When you use the $.ajax call you're using latitude and longitude declared right under the $(document).raedy() but you never assign nothing to them so they're undefined.
Hope this solve your issue.
P.S. You se the values in the alert because you're using ones from position, not from your variables.
Do not use var inside your displayPosition function. You do not want to declare new variables inside the scope of the function, you want to assign values to the existing variables you declared in the global scope earlier.

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.

Calculate driving distances Google Maps API

For a website where a user enters his address, I'm trying to find the location closest to him where the user can collect the ordered goods.
Based on the user's address I can narrow down the possible pick up locations to between 2 and 5. So I'd like to calculate the distance between user's address (point A) and the possible pick up locations.
The demo here works fine with just two addresses. I've adapted the code as much as I can to work with more than two addresses. I posted my JS code here since I can't seem to properly format it in SO.
In the code are two alerts. The first alert correctly shows the different pick up locations. But the second alert always shows the LAST pickup location.
Can anyone explain why?
HTML:
<p id="hello">Hello World</p>
JavaScript:
var geocoder, location1, location2, gDir;
function initialize(counter) {
if( counter == 0 ){
geocoder = new GClientGeocoder();
gDir = new GDirections();
}
GEvent.addListener(gDir, "load", function() {
var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
$("#results").append('<strong>Driving Distance: </strong>' + drivingDistanceKilometers + ' kilometers<br /><br />');
});
}
function getDistance(agency_add, counter) {
initialize(counter);
geocoder.getLocations(agency_add, function (response) {
if (!response || response.Status.code != 200) {
alert("Sorry, we were unable to geocode the address" + agency_add);
}
else {
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
//alert("ONE: "+location1.address);
geocoder.getLocations(document.forms[0].address1.value, function (response) {
//alert("TWO: "+location1.address);
if (!response || response.Status.code != 200) {alert("Sorry, we were unable to geocode the second address");}
else {
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
gDir.load('from: ' + location1.address + ' to: ' + location2.address);
}
});
}
});
}
$(document).ready(function(){
//put each agency address in an array
var agencies = [];
$(".agency_field").each(function(index) {
agencies.push($(this).val());
});
for (var i = 0; i < agencies.length; i++){
var res = getDistance(agencies[i], i);
}
});
you are calling geocoder.getLocations inside a loop. geocoder.getLocations runs asynchronously. when it receives the 2nd request while still processing the first, it cancels the first request.
If you want to multi-thread geocoder.getLocations you need to create multiple instances of it.

Categories