As a newcomer to Javascript, I have encountered an issue while trying to pass data to the POST method of a web API. Sometimes, I am only receiving values properly for the second response (i.e. requestOptions2), which I suspect is due to the asynchronous nature of callback functions. The problem arises because the second callback function is executed before the first one completes, leading to issues with the AJAX call. Additionally, I am facing difficulty in accessing 'JSON.stringify(points)' outside of the 'Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () )' block. I am seeking a solution to pass the 'points' data to the web API without losing any information.
Below is the Javascript code in question:
function RequestShuttle() {
Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () {
var points = [];
var searchManager = new Microsoft.Maps.Search.SearchManager(map);
var requestOptions1 = {
bounds: map.getBounds(),
where: document.getElementById("origin").value,
callback: function (answer, userData) {
map.setView({ bounds: answer.results[0].bestView });
map.entities.push(new Microsoft.Maps.Pushpin(answer.results[0].location));
points.push((answer.results[0].location));
}
};
var requestOptions2 = {
bounds: map.getBounds(),
where: document.getElementById("destination").value,
callback: function (answer, userData) {
map.setView({ bounds: answer.results[0].bestView });
map.entities.push(new Microsoft.Maps.Pushpin(answer.results[0].location));
points.push((answer.results[0].location));
console.log(JSON.stringify(points));
$.ajax({
type: "POST",
data: JSON.stringify(points),
url: "api/Trip",
contentType: "application/json"
});
}
};
searchManager.geocode(requestOptions1);
searchManager.geocode(requestOptions2);
});
}