2

I'm currently using geolocation to get the clients browser location. Right now, I store the values in local storage and then send them when the user submits the form. I would like to send them before the page even loads however, so that I can run the required calculations when the page is first opened on the client side.

Here is the javascript I am using to get the location (which works well). It runs before the page is loaded.

 navigator.geolocation.getCurrentPosition(foundLocation, noLocation);

 function foundLocation(position) {
    if (isPostBack == true) {
            return;
    }

    var lat = position.coords.latitude;
    var long = position.coords.longitude;

    this.localStorage.setItem("lat", Math.round(lat * 1000000) / 1000000);
    this.localStorage.setItem("long", Math.round(long * 1000000) / 1000000);         
 }

I then use window.onload and call the values in storage to load them on the form automatically. The user then clicks a button and the form submits with the values.

How can I just send those values directly to the server? This would allow me to run the required location calculations without the user even having to click. I know I could just automate the submit button click after after the window.onload fires, but I don't want it to look like the form loads, submits then posts back if that makes sense.

I'm new to asp.net so I'm not even sure what question to ask here so my apologies if this is something simple I'm just looking over.

EDIT: The "possible duplicate" is regarding executing js before page load which I am already doing. My question is more on how to send the values back to the server before loads complete.

Tronald
  • 1,520
  • 1
  • 13
  • 31
  • Possible duplicate of [Javascript before onload?](https://stackoverflow.com/questions/7136705/javascript-before-onload) – Scath Jun 20 '18 at 17:45
  • 1
    You won't be able to do that. You can use one empty page to perform that javascript and then post it to the server to the final page. – hardkoded Jun 20 '18 at 17:45
  • @Scath I am already running the js before onload. I'm concerned with how to get those values back to the server before onload. – Tronald Jun 20 '18 at 17:53
  • 1
    Might be able to use ajax and a web service? – Scath Jun 20 '18 at 17:54

1 Answers1

2

You can create an empty page as a first step. Then that page can perform that calculation and redirect to the final page sending that info through a POST or a GET.

window.location.href = "your-final-page.aspx?lat=" + lat + "&long=" + long;
hardkoded
  • 18,915
  • 3
  • 52
  • 64
  • 1
    Seems like the easiest route to go. Thanks, it's been interesting making the transition from WPF to ASP where I have to worry about small stuff like this now. – Tronald Jun 20 '18 at 18:02