files: index.html - simple 2 input #lat for &lng= and #lng for &lng= and the button is for ajax to run the post request to the findnearbyplacename.php.
script.js: ajax post call with 2 data fields.
$('#btnRun').click(function() {
// alert("Hello");
lat = $('lat').val();
lng = $('lng').val();
$.ajax(
{
method: "POST",
url: "libs/php/findnearbyplacename.php",
data: {
lat: $('#lat').val(),
lng: $('#lng').val(),
},
success: function(result){
console.log(result['data']);
$('#div1').html(result['data'][0]['distance'])
},
error: function(jqXHR, textStatus, errorThrown){
// error code
console.log("we have reached error ");
console.log(lat, lng);
}
});
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title> Find Nearby Place Names </title>
<meta name="author" content="Hafizullah Karim" >
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
</head>
<body>
<input type="number" id="lat" name="lat">
<input type="number" id="lng" name="lng">
<button id="btnRun">Run</button>
<br>
<div id="div1"> </div>
<script> console.log($('lat').val())</script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
findnearbyplacename.php - php curl to get a json object from the api mentioned above.
full code here https://github.com/Connector403/stage4/tree/master
<?php
$lat = $_REQUEST['lat'];
$lng = $_REQUEST['lng'];
$url = 'http://api.geonames.org/findNearbyPlaceNameJSON?formatted=true&lat'.$lat.'&lng='. $lng.'&username=sherazzi403&style=full';
// initialize the resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_POSTFIELDS)
$result = curl_exec($ch);
curl_close($ch);
// api returns data as json
// decode the json as an associative array so that we can append it to the $output
$decode = json_decode($result,true);
// the 'geonames' properrty from the serialized JSON is store into the 'data'
// element of $output
$output['data'] = $decode['geonames'];
// the correct header information for json is set and $output is converted to jsobn before send it
header('Content-Type: application/json; charset=UTF-8');
echo json_encode ($output);