-1

Api: http://api.geonames.org/findNearbyPlaceNameJSON?formatted=true&lat=47.3&lng=9&username=sherazzi403&style=full

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);
       
  • Are we suppose to guess what happens on the server side (like with your PHP?) Please read [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) and [How do I ask a good question](https://stackoverflow.com/help/how-to-ask) and edit your question accordingly. – M. Eriksson Dec 26 '20 at 22:04
  • Why does the code produce undefined in the console? – VeryConfusedSOS Dec 26 '20 at 22:37
  • I am using xampp and when I run the code it only produces undefine undefined for the 2 inputs so what is causing this issue and how can i solve it? – VeryConfusedSOS Dec 26 '20 at 22:47
  • To the undefined, ensure that you are using `#` with the jquery selectors to get the element id. The `data` section of the ajax has a stray `,` after the `lng` reference. (check the browser's console to check javascript errors, which coincidentally, the network tab there can be used to check the ajax requests too) – Paul T. Dec 27 '20 at 00:38

1 Answers1

0

Your problems stem from a missing = in your lat parameter sent to the GeoNames API.

$url = 'http://api.geonames.org/findNearbyPlaceNameJSON?formatted=true&lat'.$lat.'&lng='. $lng.'&username=sherazzi403&style=full';
                                                                                ^ 
                                                                           = missing here

Using the Network tab of your browser's debugging tools you'll see that the response coming back from the API contains just a simple message: Missing parameter. Add the = and proper results come back.

Since you're not getting back the response you're expecting, the key you're looking for is absent, hence the undefined message. You should add some error checking here.

Also, as noted in the comments, you're missing a leading # on a couple of the jQuery calls but this isn't affecting the result because you have it correct where it matters.

There's also a trailing comma (,) in your data object, but that's not troubling Firefox.