javascriptjqueryajaxandroid-webservice

Ajax succes in loop to set global variable


I want to set global variable from function and loop ajax to get distance. However the nearestIndex variable is always undefined.

First solution I got was to use async: false - this is work in my pc browser, but this project is webservice to android, and this solution not work to webview.

And of course async: false not recommended. I need this example in my case, I've been looking for this problem in stack overflow, but i always failed to understand about callback.

var allDestination = ["A", "B", "C"];
var nearestIndex;

function getNearest(){
	var from = myPosition.getLatLng().lat + "," + myPosition.getLatLng().lng;
	var tempDistance;
	for(var i=0; i<allDestination.length; i++){
		var destination = allDestination[i].getLatLng().lat + "," + allDestination[i].getLatLng().lng;
		$.ajax({
            type: "GET",
            url: "http://localhost:8989/route?point=" + from + "&point=" + destination + "&points_encoded=false&instructions=false",
            dataType: 'json',
            contentType: "application/json",
            success: function (data) {
            	var distance = data.distance;
            	if(i == 0){
            		tempDistance = distance;
            		nearestIndex = i;
            	} else {
            		if(distance < tempDistance){
            			tempDistance = distance;
            			nearestIndex = i;
            		}
            	}
            }
        });
	}
}

function onMapClick(e) {
	myPosition.setLatLng(e.latlng);         
	myPosition.addTo(map);
	getNearest();
	allDestination[nearestIndex].addTo(map);
}


Solution

  • As you are dealing with Async call; your relevant code has to get called from success handler of ajax call as follows:

    var allDestination = ["A", "B", "C"];
    var nearestIndex;
    var tempDistance;
    var successReceived = 0; //counter to keep watch on ajax success callback
    
    //modify the function signature to receive index as well as callback function
    function getNearest(index, callbackFunction) {
      var from = myPosition.getLatLng().lat + "," + myPosition.getLatLng().lng;
    
        var destination = allDestination[index].getLatLng().lat + "," + allDestination[index].getLatLng().lng;
        $.ajax({
          type: "GET",
          url: "http://localhost:8989/route?point=" + from + "&point=" + destination + "&points_encoded=false&instructions=false",
          dataType: 'json',
          contentType: "application/json",
          success: function(data) {
              successReceived++; //increment the success counter 
            var distance = data.distance;
            if (index == 0) {
              tempDistance = distance;
              nearestIndex = index;
            } else {
              if (distance < tempDistance) {
                tempDistance = distance;
                nearestIndex = index;
              }
            }
    
            //check if we got all the ajax response back. If yes then call the callback function
            if(successReceived == allDestination.length && typeof callbackFunction == 'function')
            {
                callbackFunction();
            }
          }
        });
    
    }
    
    function onMapClick(e) {
      myPosition.setLatLng(e.latlng);
      myPosition.addTo(map);
    
      for (var i = 0; i < allDestination.length; i++) {
          //pass the current index and callback function
          getNearest(i,function(){
              allDestination[nearestIndex].addTo(map);
          });
      }
    
    }