Jackson Jackson - 28 days ago 4
Ajax Question

Calling a function inside an AJAX success response?

I'm basically trying to call a function which is outside of my AJAX inside the AJAX success response.

To explain this better, this is what I have.

These are two functions:

function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(function(position) {
setMarkerPosition(userLocation, position);
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));

});

}

function clearmyWatch() {

navigator.geolocation.clearWatch(positionTimer);
}


One of them keeps watching the users location and the other one 'should' stop it.

And this is how I'm calling the
clearmyWatch();
function inside the AJAX:

$.ajax({
type:"post",
url:"TEST.PHP",
datatype:"html",
success:function(data)
{
clearmyWatch();
}
});


However, this doesn't work and the
watchCurrentPosition();
constantly running and I also get an error in my console.

The error that I am getting is this:

ReferenceError: positionTimer is not defined


Could someone please advise on this issue?

Thanks in advance.

Answer

You need to define positionTimer at global level outside of function watchCurrentPosition() like:

var positionTimer = null;

function watchCurrentPosition() {
     positionTimer = navigator.geolocation.watchPosition(function(position) {
        setMarkerPosition(userLocation, position);
        map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude)); 

    });

}

function clearmyWatch() { 
    if(positionTimer)
        navigator.geolocation.clearWatch(positionTimer);
}
Comments