views:

147

answers:

1

Hi everyone,

Below is my javascript code snippet. Its not running as expected, please help me with this.

<script type="text/javascript">

   function getCurrentLocation() {
     console.log("inside location");
     navigator.geolocation.getCurrentPosition(function(position) {
       insert_coord(new google.maps.LatLng(position.coords.latitude,position.coords.longitude)); 
       });
   }

   function insert_coord(loc) {
     var request = new XMLHttpRequest();
     request.open("POST","start.php",true);
     request.onreadystatechange = function() {
                                     callback(request);
                                  };
     request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     request.send("lat=" + encodeURIComponent(loc.lat()) + "&lng=" + encodeURIComponent(loc.lng()));

     return request;
   }

   function callback(req) {
     console.log("inside callback");
     if(req.readyState == 4)
       if(req.status == 200) {
         document.getElementById("scratch").innerHTML = "callback success";
         //window.setTimeout("getCurrentLocation()",5000);
         setTimeout(getCurrentLocation,5000);
       }
   }

getCurrentLocation(); //called on body load
</script>

What i'm trying to achieve is to send my current location to the php page every 5 seconds or so. i can see few of the coordinates in my database but after sometime it gets weird. Firebug show very weird logs like simultaneous POST's at irregular intervals.

Here's the firebug screenshot: firebug screenshot

IS there a leak in the program. please help.

EDIT: The expected outcome in the firebug console should be like this :-

inside location
POST ....
inside callback

/* 5 secs later */

inside location
POST ...
inside callback

/* keep repeating */

A: 

Probably not the problem, but I can suggest two refactorings:

Merge your two conditions in callback():

if ((req.readyState == 4) && (req.status == 200)) {

And you can shorten your setTimeout line to:

setTimeout(getCurrentLocation, 5000);

And in an effort to fix the problem, can I get you to remove the setTimeout() from callback(), and replace the call to getCurrentLocation() with it? So you're only writing "callback success" when the callback is run, nothing else.

setTimeout(getCurrentLocation, 5000); //called on body load
GlenCrawford
i made the changes you mentioned. also i need the setTimeout inside callback because i want the code to be running every 5 seconds in a loop forever. The behaviour is still not as expected. Like its shown in the firebug screenshot, sometimes the post's appear in an instant and sometimes they don't appear at all. I want to make the POST's every 5 seconds.
Raja