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.
Related
Im creating an application using google maps api that allows the user to add a marker at a specific location
but when im clicking on the map to add the location, all data i get back is correct but i get the response code of error 19...this is my code for saving the data
function saveData(lat,lng)
{
console.log("LAT:"+lat+" LNG:"+lng);
var description = document.getElementById('manual_description').value;
var formData = new FormData();
console.log("DESC:"+description);
formData.append("latitude", lat); //outputs correctly
formData.append("longitude", lng);//outputs correctly
formData.append("description", description); //outputs correctly
console.log(formData.get("latitude")+" "+formData.get("longitude")+" "+formData.get("description"));
downloadUrl(formData, function(data, responseCode) {
console.log("RESP:"+responseCode);
console.log(data.length);
if (responseCode === 200 && data.length > 1) {
var markerId = getMarkerUniqueId(lat,lng); // get marker id by using clicked point's coordinate
var manual_marker = markers[markerId]; // find marker
manual_marker.setIcon(purple_icon);
infowindow.close();
infowindow.setContent("<div style=' color: purple; font-size: 25px;'> Waiting for admin confirm!!</div>");
infowindow.open(map, manual_marker);
}else{
console.log("RESPONSECODE: "+ responseCode); //419
console.log("DATA: "+data); //html data with title of Page Expired
infowindow.setContent("<div style='color: red; font-size: 25px;'>Inserting Errors</div>");
}
});
function downloadUrl(formData, callback)
{
var xhttp = new XMLHttpRequest;
xhttp.onreadystatechange = function() {
console.log(xhttp.readyState);
if (xhttp.readyState == 4) {
callback(xhttp.responseText, xhttp.status);
}
};
xhttp.open("POST", "http://localhost/cacheFinder/public/save");
xhttp.setRequestHeader('X-CSRF-TOKEN', '{{ csrf_token() }}');
xhttp.send(formData);
}
this is my route Route::post('save', 'MarkersController#save');
and this is the save function :
public function save(Request $request){
$lat = $request->input("latitude");
$lng = $request->input("longitude");
$description = $request->input("description");
Marker::create([
'latitude'=>$lat,
'longitude'=>$lng,
'description'=>$description
]);
return redirect('usermap');
}
Any help would be much appreciated
add this to your VerifyCsrfToken middleware
protected $except = [
'/cacheFinder/public/*'
];
or
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader('X-CSRF-TOKEN',window.Cookies.get('_csrf'));
this is because of https://laravel.com/docs/5.7/csrf disable route protection in CsrfMiddleware or post valid value
I am trying to get lat and long info from Google Geocoder, but although the information is properly extracted on the call that is being done, for some reason the js variable gets empty imediately after getting to my second alert on this piece of code (the one outside "if" condition):
var map, marker, latLong;
var geocoderlat = new google.maps.Geocoder();
var addresslat = '<?php echo str_replace(" ","+",$address);?>';
function initMap() {
geocoderlat.geocode( { 'address': addresslat}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLong = results[0].geometry.location;
alert("Inside IF: "+latLong);
} else {
latLong = '<?php echo $latitude.",".$longitude;?>';
}
})
alert("Outside: "+latLong);
var isDraggable = !('ontouchstart' in document.documentElement);
var mapOptions = {
center: new google.maps.LatLng(latLong),
zoom: 12,
(...)
Obviously there's a lot of code besides this part, but the rest of the code doesn't matter in this case because this variable is never again used anywhere in my code (I even searched with Agent Ransack all over the files so be sure that this variable was not being used anywhere else).
EDIT:
Ok, this is really, really weird...
function getGeoLatLong(addresslat) {
geocoderlat.geocode( { 'address': addresslat}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
return results[0].geometry.location;
} else {
return '<?php echo $latitude.",".$longitude;?>';
}
})
}
alert("Outside function: "+getGeoLatLong(addresslat));
This still returns "undefined" in the alert.
geocoderlat.geocode is taking more time to execute while the code execution has already reached your second alert. you need to use setTimeout to check the results or try this.
function initMap() {
geocoderlat.geocode( { 'address': addresslat}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLong = results[0].geometry.location;
alert("Inside IF: "+latLong);
alert("Outside: "+latLong);
var isDraggable = !('ontouchstart' in document.documentElement);
var mapOptions = {
center: new google.maps.LatLng(latLong),
zoom: 12,
(...)
} else {
latLong = '<?php echo $latitude.",".$longitude;?>';
}
})
Also, if you want to use latLong = '<?php echo $latitude.",".$longitude;?>'; as the default latLong you need to declare it at the top. then it will be anyways overridden when geocode finishes loading
EDIT
Try this.
function getGeoLatLong(addresslat) {
geocoderlat.geocode( { 'address': addresslat}, checkresults)
}
function checkresults(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("Outside function: " + results[0].geometry.location);
//declare the big chunk of code as a function and make a call to it.
} else {
alert("Outside function: <?php echo $latitude.','.$longitude;?>");
//declare the big chunk of code as a function and make a call to it.
}
}
getGeoLatLong(addresslat);
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.
I am creating a weather widget using javascript . In this widget the user can select the town they wish to see and the widget will display outlook , min and max temperature without refreshing using ajax . I have stored the city information in a database and had written PHP script to retrieve the data and pass it to js as JSON object
<?php
/**************************
* code to connect to your database here
*/
$con = mysqli_connect("localhost", "user", "pass");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL:".mysqli_connect_error();
}
mysqli_select_db("weather", $con);
$town = $_GET['town'];
/***************************
*
* Query the DB for weather information for the given town.
*
* A PHP array object containing the weather data.
* Return a JSON encoded version of the array to the browser.
*
*/
$sql = "SELECT * from weather where town = $town";
$result = mysqli_query($sql);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$arr = array(
"town" => $row[town],
"outlook" => $row[outlook],
"min_temp" => $row[min_temp],
"max_temp" => $row[max_temp]
);
}
echo json_encode($arr);
mysqli_close();
?>
And in js i want to show the weather only for selected town . How to parse the JSON object to get only the information of the town selected by the user . Like
if(jsondata == "sydney")
return "sydney information";
I did this using DOJO as
var data;
dojo.xhrGet({
// The URL to request
url: "PHP/weather.php?town=" + ntown,
sync: true,
handleAs: 'json',
// The method that handles the request's successful result
// Handle the response any way you'd like!
load: function(result) {
data = result;
}
});
return data;
}
However , i dont want to use dojo . how do i do that . Any suggestions ?
Suppose you have a select tag with id "town".
<select id="town" onchange="handler(this)"></select>
Now, for the Javascript part. You need to use XMLHttpRequest to make an ajax call.
function handler(elem){
var tname = elem.value;
var request_url = "PHP/weather.php?town=" + tname;
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Some error occured");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
//Update your page here
}
}
http_request.open("GET", request_url);
http_request.send();
}
<body>
<div id="townInfo">
<div id="town"></div>
<div id="outlook"></div>
<div id="min_temp"></div>
<div id="max_temp"></div>
</div>
<script>
var town = document.getElementById('town');
var outlook = document.getElementById('outlook');
var min_temp = document.getElementById('min_temp');
var max_temp = document.getElementById('max_temp');
var data;
dojo.xhrGet({
// The URL to request
url: "PHP/weather.php?town=" + ntown,
sync: true,
handleAs: 'json',
load: function(result) {
data = result;
town.innerHtml = data['town'];
outlook.innerHtml = data['outlook'];
min_temp.innerHtml = data['min_temp'];
max_temp.innerHtml = data['max_temp'];
}
});
</script>
</body>
warning: not tested
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.