Reputation: 37
I send an Ajax request to a PHP file which sends a CURL request to an API and then return the results.
The PHP code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.example.com?country=usa');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$response = array('result' => $result);
echo json_encode($response);
Javascript/jQuery code:
$.ajax({
url: "file.php",
type: "POST",
dataType : "json",
success: function(data){
console.log(typeof(data.result));
console.log(data.result);
}
});
The type of the result is string
and the result looks like:
{"results":[{"code2":"093","code1":"NY","lng":-73.9395687,"name1":"New York","lat":42.8142432}]}
How to get the lng
and lat
from that result?
Upvotes: 1
Views: 1141
Reputation: 4005
var data = {"results":[{"code2":"093","code1":"NY","lng":-73.9395687,"name1":"New York","lat":42.8142432}]}
console.log(data.results[0].lat);
console.log(data.results[0].lng);
data.results
is array therefore use [0]
to get first element of Array:
data.result[0]
And then get contents of first element:
data.result[0].lat
Ajax:
$.ajax({
url: "file.php",
type: "POST",
dataType : "json",
success: function(data){
console.log(data.result[0].lat);
console.log(data.result[0].lng);
}
});
Upvotes: 1
Reputation: 337626
As the proxy is returning the response from the third party API as a JSON encoded string you need to manually deserialise it. You can do that by using JSON.parse()
. Then you can access the objects within the results
array by index. Try this:
var data = {
result: '{"results":[{"code2":"093","code1":"NY","lng":-73.9395687,"name1":"New York","lat":42.8142432}]}'
}
// inside your AJAX callback:
var obj = JSON.parse(data.result);
var lat = obj.results[0].lat;
var lng = obj.results[0].lng;
console.log(lat);
console.log(lng);
Upvotes: 2