html - Ajax call to php curl produce undefined ← (PHP, JavaScript, JQuery, HTML)

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>

Answer



Solution:

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.

Source