Skip to content
Advertisement

Ajax PHP placing variables in string for API call

I have read and attempted to implement all solutions I found on the web but until now I can’t get this to work, so time to ask for help:

I send the following Ajax call to my PHP file:

        $.ajax({
            url: "libs/php/geolocate.php",
            type: 'POST',
            dataType: 'json',
            data: {
                lat: $lat,
                lon: $lon
            },

this invokes the following call in the php file:

$result = $geocoder->geocode( '51.952659, 7.632473' );

Everything works okay, but what I’d like to do next is replace the preformatted coords, with those that I send across in the ajax call. This is where I am failing, I have tried varying methods to inject lat and lon including logic from a prior project: $_REQUEST['lat'], nothing seems to work.

Can someone please advise what format I need to use?

many thanks

EDIT var_dump() output:

<pre class='xdebug-var-dump' dir='ltr'>
<small>C:wamp64wwwgeonamesExamplelibsphpgeolocate.php:2:</small>
<b>array</b> <i>(size=0)</i>
  <i><font color='#888a85'>empty</font></i>
</pre>{"results":[{"source":"opencage","formatted":"Friedrich-Ebert-Straße 7, 48153 Münster, Germany","geometry":{"lat":51.9526599,"lng":7.632473},"countryCode":"DE","timezone":"Europe/Berlin","roadinfo":{"sideOfRoad":"right","speed":"km/h"},"currency":{"name":"Euro","symbol":"€"}}]}```

Advertisement

Answer

You can use $_POST['lat'] and $_POST['lon']

$result = $geocoder->geocode( $_POST['lat'] . ', ' . $_POST['lon']);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement