So folks, what I am trying to do is populate a really simple HTML page with some info from the Geonames API. It is my first time using cURL in this way so some help would be appreciated. My current code gets the data from the api but then instead of updating the HTML it redirects the page to the JSON page.
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true);
$url='http://api.geonames.org/oceanJSON?formatted=true&lat=' . $_REQUEST['oceanlat'] . '&lng=' . $_REQUEST['oceanlng'] . '&username=CHANGEDstyle=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['ocean'] = $decode['ocean'];
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);
?>
$('#oceansub').click(function(/*e*/) {
//e.preventDefault();
$.ajax({
url: "php\nearestOcean.php",
type: 'POST',
dataType: 'json',
ocean: {
lat: $('#oceanlat').val(),
long: $('#oceanlng').val()
},
success: function(result) {
console.log(JSON.stringify(result));
if (result.status.name == "ok") {
$('#txtDistance').html(result['ocean']['distance']);
$('#txtGeonameID').html(result['ocean']['geonameId']);
$('#txtName').html(result['ocean']['name']);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Please enter a lat or long that is over water.")
}
});
});
I tried to use preventDefault()
in the AJAX to stop the submit button from actually performing, but that didn't work, that's why it is commented out.
I feel like there is a stupidly easy reason for this, but I am totally frazzled now. The image is the page that I get to. But what I was expecting what the info to be inserted into my HTML as per the jQuery/Ajax.
I am assuming that my HTML isnt the issue, as I have just ID'd some <p>
elements to try and get some easy output.
You'll have to excuse the rubbish IDs they're only temporary while I get the code to work. If you need more info let me know, thanks in advance :)
Update: I have added the proper console errors to the block at the bottom of the Ajax, something in the success block isn't working. Even though I do get code: '200'
and name: 'ok'
?
CodePudding user response:
Turns out that all of the code here was mostly fine, it turns out when using VS Code when copying the relative paths to files for some reason it was using backslashes instead of frontslashes -.- I have learnt this lesson the hard way, imma check the paths in future.