There are two files in my project: one file contains PHP code (which is functioning correctly) and the other file contains JavaScript code. The issue lies within the JavaScript file:
function calcDistance() {
var city = $("#txtpartenza").val();
$.ajax({
type: "POST",
url: 'showDepartures.php',
dataType: "json",
success: function (data) {
$.each(data, function (index) {
var departure = data[index];
findGeo(city, departure);
});
}
});
}
function findGeo(departure, destination) {
var latDeparture;
var lonDeparture;
var latDestination;
var lonDestination;
console.log(departure);
console.log(destination);
var xmlhttpDeparture = new XMLHttpRequest();
var xmlhttpDestination = new XMLHttpRequest();
xmlhttpDeparture.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext="+departure+"&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
xmlhttpDestination.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext="+destination+"&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
xmlhttpDeparture.send();
xmlhttpDestination.send();
xmlhttpDeparture.onreadystatechange = function () {
if (xmlhttpDeparture.readyState == 4 && xmlhttpDeparture.status == 200) {
xmlhttpDestination.onreadystatechange = function () {
if (xmlhttpDestination.readyState == 4 && xmlhttpDestination.status == 200) {
var resDeparture = JSON.parse(xmlhttpDeparture.responseText);
latDeparture = resDeparture.Response.View[0].Result[0].Location.DisplayPosition.Latitude;
lonDeparture = resDeparture.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
var resDestination = JSON.parse(xmlhttpDestination.responseText);
latDestination = resDestination.Response.View[0].Result[0].Location.DisplayPosition.Latitude;
lonDestination = resDestination.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
console.log(latDeparture);
}
};
}
};
}
The Ajax function is functioning as expected; I am able to call findGeo(city, departure)
without any issues. However, within the findGeo(departure, destination)
function, the XMLHttpRequest
for "departure" is encountering problems. The variable latDeparture
is not being printed in the console and the code inside the
xmlhttpDeparture.onreadystatechange = [...]
block is not being executed.
Just to provide a full picture, here is the essential part of the PHP file:
$i = 0;
$city = array();
while ($rows = $result->fetch_assoc()) {
$city[$i] = $rows['departure'];
$i=$i+1;
}
echo json_encode($city);