Reputation: 28545
Im trying to execute some jquery before a form is submitted.
The aim is to obtain user location, and save the coordinates before the form gets posted.
but it happens too quickly and doesn't seem like it is being fully executed. the popup for sharing location shows for a split second the the form posts before i can answer yes to sharing location
$("#DepotSearchForm").submit(function () {
// your code here
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
$('#Latitude').val(position.coords.latitude);
$('#Longitude').val(position.coords.longitude);
alert(position.coords.latitude + ", " + position.coords.longitude);
//gmap.setCenter(pos);
}, function () {
//alert("Unable to determine location");
//return false;
});
}
// }
});
Upvotes: 1
Views: 105
Reputation: 171669
geolocation
is asynchronous so indeed your form is being submitted before it completes.
Choices would be to set the location values when page loads or you can prevent the jQuery submit event and use the native submit when the geolocation has completed.
$("#DepotSearchForm").submit(function(event) {
// prevent jQuery submit occurrung
event.preventDefault();
var form = this;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$('#Latitude').val(position.coords.latitude);
$('#Longitude').val(position.coords.longitude);
alert(position.coords.latitude + ", " + position.coords.longitude);
// tigger native submit
form.submit();
}, function() {
// handle geolocation error
});
}
});
You should also do something in UI to indicate form is being processed and prevent user from submitting again while geolocation is being processed
Upvotes: 1