简体   繁体   中英

Javascript function on submit button - Wait for it to complete

I want to trigger a function when the submit button is pressed on the form and wait for the javascript function to complete, then continue the form submission. I dont want the form to submit before the javascript function has completed.**

This is what I have at the moment: http://jsfiddle.net/njDvn/68/

function autosuggest() {
var input = document.getElementById('location');
    var options = {
    types: [],
    };
    var autocomplete = new google.maps.places.Autocomplete(input, options);
}

<!-- Get lat / long -->      
function getLatLng() {
    var geocoder = new google.maps.Geocoder();
    var address = document.getElementById('location').value;
    geocoder.geocode({
        'address': address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latLng = results[0].geometry.location;
            $('#lat').val(results[0].geometry.location.lat());
            $('#lng').val(results[0].geometry.location.lng());
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

<!-- Load it --> 
window.onload = autosuggest;

First you need to prevent the form to be submitted, add a return false at the end of getLatLng() function.

Then when the geocoding is done, submit the form manually with document.getElementsByTagName('form')[0].submit()

Here's an updated jsfiddle: http://jsfiddle.net/njDvn/70/

You can intercept the form submission, abort it and send the geocoding request to Google.

When the server responds, you can re-submit the form from the callback (or display an error in case of failure).

Store the state of the request somewhere (for the sake of simplicity, I'm using a global variable in my example). In this case, it's just a flag that indicates whether or not the geocoding request was completed successfully (so that now, when the form is submitted and the listener is re-triggered, it will know not to re-send the geocoding request).

http://jsfiddle.net/njDvn/75/

Feel free to remove the console logging.

You may also want to make the lat/long fields hidden.

var GeoCoded = {done: false}; // this holds the status of the geo-coding request

$(document).ready(function(){
    autosuggest(); // place your auto-suggest (now called autocomplete) box

    $('#myform').on('submit',function(e){

        if(GeoCoded.done)
            return true;

        e.preventDefault();
        console.log('submit stopped');
        var geocoder = new google.maps.Geocoder();
        var address = document.getElementById('location').value;

        // disable the submit button
        $('#myform input[type="submit"]').attr('disabled',true);

        // send the request
        geocoder.geocode({
            'address': address
        },
        function (results, status) {
            // update the status on success
            if (status == google.maps.GeocoderStatus.OK) {
                var latLng = results[0].geometry.location;
                $('#lat').val(results[0].geometry.location.lat());
                $('#lng').val(results[0].geometry.location.lng());
                // if you only want to submit in the event of successful 
                // geocoding, you can only trigger submission here.
                GeoCoded.done = true; // this will prevent an infinite loop
                $('#myform').submit();
            } else { // failure
                console.log("Geocode was not successful for the following reason: " + status);
                //enable the submit button
                $('#myform input[type="submit"]').attr('disabled',false);
            }


        });        

    });   

});
myFunction = new function(callback) {
    $.ajax({...}).done(callback());
}

myFunction(new function() {
    getLatLng();
});

Here you need to call myFunction onSubmit event.

As MasterAM has stated, all you need do is the following:

/// I've included the following function to allow you to bind events in a 
/// better way than using the .onevent = function(){} method.
var addEvent = (function(){
  if ( window.addEventListener ) {
    return function(elm, eventName, listener, useCapture){
      return elm.addEventListener(eventName,listener,useCapture||false);
    };
  }
  else if ( window.attachEvent ) {
    return function(elm, eventName, listener){
      return elm.attachEvent('on'+eventName,listener);
    };
  }
})();

/// add another window.onload listener
addEvent(window,'load',function(){
  /// find the form, obviously should use whatever id you have on your form
  var form = document.getElementById('my_form');
      form.preventSubmit = true;
  /// add our onsubmit handler
  addEvent(form,'submit',function(e){
    /// only stop the form if we haven't already
    if ( form.preventSubmit ) {
      /// place/call whatever code you need to fire before submit here.
      alert('submit was blocked!');
      /// after that code is complete you can use the following
      form.preventSubmit = false;
      form.submit();
      /// return false prevents the submit from happening
      return false;
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM