Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this javascript getting called twice?

I have a button where I've hooked the onclick to a call to retrieve the users location and then use the location to make another call to retrieve a list of nearby locations. For some reason the geolocation success method is being called twice on the second click of the button.

So I load the page, click the button, allow permission to use my location, and it will make one ajax request to get the nearby locations. This works fine.

I click the button again, allow permission to use my location (again), it will make one ajax request to get the locations, wait ~2 seconds, and then make another request using the same coordinates without me allowing permission. So the success method has to be getting called twice, but I'm not sure why.

$("#FindLocation").click(function () {
  myScript.findNearbyLocations(displayData, displayError);
});

This click function is not being called twice and I've commented out all the code in displayData and displayError.

findNearbyLocations: function (onSuccess, onFailure) {
  if (navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function (position) {
      alert('This is getting called twice except on the initial call.');
      myScript.findStores(position.coords.latitude, position.coords.longitude, onSuccess, onFailure);
    }, function () {
      onFailure(true);
    });
  }
}

Anyone see where I've gone wrong?

Edit: I don't think the markup is the problem. I'm only using basic webpages for testing. There is no styling or other elements at the moment.

<form id="form1" runat="server">
  <div>      
    <MyControls:Search ID="Search" runat="server" />
  </div>
</form>

and the user control (along with all the necessary javascript includes)

<script type="text/javascript">
  $(document).ready(function () {
    $("#FindLocation").click(function () {
      myScript.findNearbyLocations(displayData, displayError);
    });
  });
</script>

<input type="button" id="FindLocation" value="Find Location" />
<div id="results">
</div>
like image 948
Brandon Avatar asked Jan 07 '11 15:01

Brandon


1 Answers

Could be a bug in the getCurrentPosition of whatever client you are using. In that case you could simply set a flag when the success method is called and not allow the findStores function to be called a 2nd time.

like image 116
wosis Avatar answered Oct 30 '22 08:10

wosis