简体   繁体   中英

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:\wamp64\www\geonamesExample\libs\php\geolocate.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":"€"}}]}```

您可以使用$_POST['lat']$_POST['lon']

$result = $geocoder->geocode( $_POST['lat'] . ', ' . $_POST['lon']);

Usually php passes automatically variables with the header

application/x-www-form-urlencoded

To retrieve the values with your current setup you need to capture the data using

php://input

Ie

$data = file_get_contents('php://input') ;

var_dump($data); // associative array with your variables

More info here

PHP "php://input" vs $_POST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM