Question

I have a form which onsubmit performs some functions. How can I be sure that func2(); is only performed if func1(); run successfully? And func3(); only if 2 and 1 did?

<form onsubmit="func1();func2();func3(); return false">
    <input type="text" id="start" name="start">
    <input type="submit" value="Go">
</form>

For example one of the functions is like:

<script src="https://maps.googleapis.com/maps/api/js?&amp;sensor=false&amp;region=it&amp;libraries=places"></script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var myLatlng = new google.maps.LatLng(41.88994,12.51383);

var mapOptions = {
    zoom:16,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: myLatlng,
    styles: [
        {
            featureType: "poi.business",
            elementType: "labels",
            stylers: [
                    { visibility: "off" }
            ]
        }
    ]
  }

map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));

var input = document.getElementById('start');
var options = {
    types: ['geocode'],
    componentRestrictions: {country: 'it'},
    rankBy: google.maps.places.RankBy.DISTANCE
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.bindTo('bounds', map);

var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: 'Studio medico'
});
}

function calcRoute() {
    var start = document.getElementById('start').value;
    var end = "Via Tiburtina 500, Roma";
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.TRANSIT
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
}

google.maps.event.addDomListener(window, 'load', initialize);

Other 2 are:

function boxappear() {
document.getElementById("percorsolink").style.display="none";
document.getElementById("percorsoform").style.display="inline";
}

function reducemap() {
document.getElementById("map-canvas").style.width="620px";
google.maps.event.trigger( map, "resize" );
}
Was it helpful?

Solution

It seems it's not about running one function if the other one is succesful, but after an asynchronous operation is done. In calcRoute, the route calculation API call is asynchronous; that means the function will return before the directionsService finishes creating the route. One solution is to modify calcRoute to take a callback:

function calcRoute(callback) {
    var start = document.getElementById('start').value;
    var end = "Via Tiburtina 500, Roma";
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.TRANSIT
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);

        // If a callback was passed, run it
        if(typeof callback === "function") {
            callback();
        }

      }
    });
}

Then change your function call to pass the callback:

<form onsubmit="calcRoute(function(){ boxappear(); reducemap(); }); return false">

Side note: I wouldn't recommend inlining code in HTML attributes like that, is mixes structure and behavior, and can also become hard to maintain; I suggest looking into other ways of attaching events to DOM elements.

OTHER TIPS

When you say "run successfully" do you mean completed? This is guaranteed, since your onsubmit is basically like a function body. You're not telling onsubmit to run the functions in parallel or giving it a list; rather, you're just executing them in sequence.

You can change your functions to return true (success) or false (something went wrong).

function func1() {
  // do something
  return true;
}

function func2() {
  // do something
  if (!'someThingWentWrong') { return fale; }
  return true;
}

...

Then chain your functions like this in your form:

<form onsubmit="func1() && func2() && func3(); return false">
    <input type="text" id="start" name="start">
    <input type="submit" value="Go">
</form>

The && is the and operator. It first evaluates its first argument, and only if the first argument is true the second argument is evaluated. So, the &&-chain stops, when the first function returns false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top