0

I am new to Javascript,so this question might be a basic one. I am trying to pass data to POST method of a web API but I am not receiving values properly everytime. I see that javascript is sending the only the second response sometimes (i.e. only requestOptions2) which I think is due to the callback function. (As it doesn't wait till the completion for first callback function to execute the second callback function and post and AJAX call.) Also, I cannot access 'JSON.stringify(points) out of Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () ) so, I am looking for a way to pass that 'points' data to web API without losing information.

This is my Javascript code:

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);
    });
}
Sree
  • 973
  • 2
  • 14
  • 32

1 Answers1

0

I stole this answer from: this post

Here's probably the way to structure your code:

function first() {
   return $.ajax(...);
}

function second(data, textStatus, jqXHR) {
   return $.ajax(...);
}

function third(data, textStatus, jqXHR) {
   return $.ajax(...);
}

function main() {
    first().then(second).then(third);
}
Rick Riggs
  • 336
  • 2
  • 12