Setting a variable with javascript submit with form

991 views Asked by At

I have three hidden variables on a form. I have to set these variables using a javascript function then I have to reload the page so I can use the form variables with some php code.

The problem I'm having is that, first, I don't know when I should call the javascript function. I managed to call it once I submit the form but then I can't get the page to refresh. So then I let the javascript function run when the page is first loaded but then I think the variables of the hidden fields are not properly set.

Here is my javascript code, the first version. In this version I have a gps function which is called once the form is submitted.

<script>

function gps(){
    if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(GetLocation, showError);
    }
    else {
      alert('Geolocation is not supported for this Browser/OS version yet.');
    }

}

function GetLocation(location) {

    document.getElementById("latitude").value=location.coords.latitude;
    document.getElementById("longitude").value=location.coords.longitude;
    document.getElementById("accuracy").value=location.coords.accuracy;

}

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}
</script>

And this is my form code simplified

<form id="emoteForm" action="" onsubmit="gps(); return false;" target="_top" method="post" name="emote">

<input hidden="true" type="text" id="latitude" name="latitude">
<input hidden="true" type="text" id="longitude" name="longitude">
<input hidden="true" type="text" id="accuracy" name="accuracy">

<h4><input id="but" class="btn btn-primary btn-lg" role="button" value="Submit" type="submit" name="submit" onclick="show('form'); return FALSE;"></h4>

</form>

Now this is the php code that is before the html code of this page and that I have to run after the submission of the form.

<?PHP

session_start();

if(!isset($latitude)){
    echo "Do something";
}

if(postvar("submit")=="Submit"){
     echo "Submitting";
}

?>

So when I first load the page I get the "Do something" text which is fine since the latitude variable is still not set. When I hit the Submit button I get asked to allow to get my GPS location since it is calling the gps() function. In this function the variables latitude, longitude and accuracy are set. But then the page doesn't reload.

How can I then do both things, set the variable values when I submit then reload the page and keep the values so I can use them with my php code. Any ideas?

EDIT 1:

Added code to control if location is already set

<script>

function gps(){
    if (navigator.geolocation) {
      if (typeof localStorage['authorizedGeoLocation'] == "undefined" || localStorage['authorizedGeoLocation'] == "0") {
      navigator.geolocation.getCurrentPosition(GetLocation, showError);
      return false;
      }else{
      return true;}
    }
    else {
      alert('Geolocation is not supported for this Browser/OS version yet.');
    }

}

function GetLocation(location) {

    document.getElementById("latitude").value=location.coords.latitude;
    document.getElementById("longitude").value=location.coords.longitude;
    document.getElementById("accuracy").value=location.coords.accuracy;

    localStorage['authorizedGeoLocation'] = 1;

    document.getElementById("emoteForm").submit();

}

}

function showError(error) {
    localStorage['authorizedGeoLocation'] = 0;
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}
</script>
2

There are 2 answers

0
Atirag On BEST ANSWER

I finally managed to solve this by getting the location data before submitting the form. So I got rid of the gps() function and submitted the form normally. Like this.

<script>

if (navigator.geolocation) {
  document.getElementById("but").disabled = true;
  document.getElementById("but").value = "GPS information is loading";
  navigator.geolocation.getCurrentPosition(GetLocation, showError);
}
else {
  document.getElementById("but").disabled = true;
  document.getElementById("but").value = "No GPS information";
  alert('Geolocation is not supported for this Browser/OS version yet.');
}

function GetLocation(location) {

    document.getElementById("latitude").value=location.coords.latitude;
    document.getElementById("longitude").value=location.coords.longitude;
    document.getElementById("accuracy").value=location.coords.accuracy;

    document.getElementById("but").disabled = false;  
    document.getElementById("but").value = "Submit";
}

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}
</script>
7
jeroen On

You are cancelling the form submission when you use onsubmit="gps(); return false;" and that is correct; the getCurrentPosition() is asynchronous so you have to wait until it is finished, you can't submit the form right away.

When getCurrentPosition() is finished, the GetLocation() function gets called and the variables are filled in. Now you can submit the form so that a request to the server is made that includes the newly set values:

function GetLocation(location) {

    document.getElementById("latitude").value=location.coords.latitude;
    document.getElementById("longitude").value=location.coords.longitude;
    document.getElementById("accuracy").value=location.coords.accuracy;

    // submit the form
    document.getElementById('emoteForm').submit();

}

Note that this could take some time, so you should probably show your visitor a message that the form is being submitted, disable the submit button, etc..