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;
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.