I'm working on a simple AJAX call to retrieve API data from the Geonames website, but I keep getting this error:
Warning: Undefined array key "geonames" in C:\xampp\htdocs\task\libs\php\ocean.php on line 25
{"status":{"code":"200","name":"ok","description":"success","returnedIn":"72 ms"},"data":null}
As you can see, the status code is returning okay but I can't access the data in the array and keep getting the null response.
Javascript:
$('#oeanBtnRun').click(function() {
$.ajax({
url: "Oceanlibs/php/ocean.php",
type: 'POST',
dataType: 'json',
data: {
lat: $('#selLat').val(),
lng: $('#selLng').val(),
},
success: function(result) {
console.log(JSON.stringify(result));
if (result.status.name == "ok") {
$('#results').html(result['data']);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}
});
});
html:
<tr>
<td>2. Get Ocean</td>
<td>
<label>Latitude: </label><input id="selLat" type="number"></input>
<label>Longitude: </label><input id="selLng" type="number"></input>
</td>
<td><button class="oceanBtnRun">Run</button></td>
</tr>
php:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true);
$url='http://api.geonames.org/neighbourhoodJSON?formatted=true&lat=' . $_REQUEST['lat'] . '&lng=' . $_REQUEST['lng'] .'&username=kerriemcivor92&style=full';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$decode = json_decode($result,true);
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
$output['data'] = $decode['geonames'];
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);
?>
I've tried changing
$output['data'] = $decode['geonames'];
to various forms with zero success.
Any ideas would be greatly appreciated!