简体   繁体   中英

Delay form submission until location is retrieved

I have an application that attempts to get locations settings from the browser, this tends to take a little while so I want it to run when the page loads. However, if you click the submit button before the location callback has run, you have no location data. My question is simple, how do I wait for my location success callback to finish before submitting my form? (without something silly like a sleep statement).
Ideally I'd like to flash a busy indicator and wait for the data. Is this possible? I have the code to make a busy indicator visible, but am not sure how I can elegantly wait for the data to be available.

$(document).ready(function(){
    var lat = "";
    var lng = "";
    var accuracy = "";
    var locationFound = false;

    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function positionSuccess(loc){
            lat = loc.coords.latitude;
            lng = loc.coords.longitude;
            accuracy = loc.coords.accuracy;
            locationFound = true;               
        });
    }else{
        alert("I'm sorry, your jerk browser doesn't support geolocation");
        locationFound = true;
    }

$('#locForm').submit(function(e){  

        $('#lat').val(lat);
        $('#lng').val(lng);
        $('#boundary').val($('#boundary-select').val());
}

Disable the submit button until the location data has been passed.

$('input[type="submit"]').attr('disabled','disabled');

Then enable the submit button

$('input[type="submit"]').removeAttr('disabled');

If the location plugin you're using doesn't have a callback function available, then you would need to bind the results to the page somehow and check against it before the user submits.

One way is binding the results of the location to the form, then only allow the form to submit when there is a location there. Here is an example of using .data() to accomplish this.

    $(document).ready(function(){
        var lat = "";
        var lng = "";
        var accuracy = "";
        var locationFound = false;

        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(function positionSuccess(loc){
                lat = loc.coords.latitude;
                lng = loc.coords.longitude;
                accuracy = loc.coords.accuracy;
                locationFound = true;  

                //bind the results to the form object using data()
                $("#locForm").data('lat' , lat)
                $("#locForm").data('lng' , lng)
                $("#locForm").data('accuracy' , accuracy)
                $("#locForm").data('locationFound' , locationFound)

            });
        }else{
            alert("I'm sorry, your jerk browser doesn't support geolocation");
            locationFound = true;
        }

    $('#locForm').submit(function(e){  

            e.preventDefault(); //prevents the normal submit

            if ( $("#locForm").data('lat') == "" || 
                 $("#locForm").data('lng') == "" || 
                 $("#locForm").data('accuracy') == "" || 
                 $("#locForm").data('locationFound') == ""
                ) {
             alert("Please wait for the browser to detect your location.");   
             return false;
                }
            else {       
              $.post( $(this).attr('action'),  $(this).serialize(), function(data){ 
                       // your callback data from the submit here
               } ); 
            }



    }

Added this code which checks every second for a value in from your location plugin:

  function wait4location() {

            if ( $("#locForm").data('lat') == "" || 
                 $("#locForm").data('lng') == "" || 
                 $("#locForm").data('accuracy') == "" || 
                 $("#locForm").data('locationFound') == ""
                ) {
                   x = setTimeout('wait4location()',1000) //every second
              } else { 
                  $("#loading").hide();
                  return false; 
                }
  }

  $("#loading").show();
  wait4location();

Use two semaphores:

var geoLoaded = false,
    submittingForm = false;

function LoadGeoData() {
    // .. your load code
    geoLoaded = true;
    ReallySubmitForm();
}

$('form').submit(function(e) {
    // .. your code
    submittingForm = true;
    ReallySubmitForm();
})

function ReallySubmitForm() {
    if (submittingForm && geoLoaded) {
        // .. your submit code
    } else {
        // .. trigger loading code
    }
}

This way, the user will see the loading image only if the Geo Data has not fully loaded by the time they submit the form. You will notice that it doesn't matter which event gets triggered first, it will only go through when both are done.

You can add a submit function to the form after the location is returned.

Here is a snippet of code that worked for me.

HTML

<form id="form" action="" method="POST">

JavaScript

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "<input type=hidden name=lat id=lat value=" + 
        position.coords.latitude + "><input type=hidden name=lng id=lng value=" 
        + position.coords.longitude + ">";
    document.getElementById("form").submit();
}

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