Tronald
Tronald

Reputation: 1585

Send javascript values to server before page load in asp.net

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.

Upvotes: 2

Views: 419

Answers (1)

hardkoded
hardkoded

Reputation: 21695

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;

Upvotes: 2

Related Questions