Can't seem to get this javascript redirect to work?
Suggestions?
Should I maybe do it with a meta refresh and how?
// If we have a successful location update
function onGeoSuccess(event)
{
document.getElementById("Latitude").value = event.coords.latitude;
document.getElementById("Longitude").value = event.coords.longitude;
document.getElementById("location").href = "track.cfm?track=s&Lat=" + event.coords.latitude + "&Long=" + event.coords.longitude;
var redirectUrl = "track.cfm?track=s&Lat=" + event.coords.latitude + "&Long=" + event.coords.longitude;
}
// If something has gone wrong with the geolocation request
function onGeoError(event)
{
alert("Error code " + event.code + ". " + event.message);
}
function redirect()
{
window.location = redirectUrl;
}
setTimeout(redirect,15000);
The problem is the scope of redirectUrl
variable. You declared redirectUrl
as local for onGeoSuccess
function, so it will be visible only inside of it. For workaround ,you can put all this stuff:
function redirect()
{
window.location = redirectUrl;
}
setTimeout(redirect,15000);
inside of onGeoSuccess
function, or make redirectUrl
global, by removing var
before redirectUrl
:
redirectUrl = "track.cfm?track=s&Lat="+...
//^-----no 'var'
Declare redirectUrl
in parent scope, and run onGeoSuccess
function.
var redirectUrl;
function onGeoSuccess (event) {
document.getElementById("Latitude").value = event.coords.latitude;
document.getElementById("Longitude").value = event.coords.longitude;
document.getElementById("location").href = "track.cfm?track=s&Lat=" + event.coords.latitude + "&Long=" + event.coords.longitude;
redirectUrl = "track.cfm?track=s&Lat=" + event.coords.latitude + "&Long=" + event.coords.longitude;
}
function onGeoError (event) {
alert("Error code " + event.code + ". " + event.message);
}
function redirect () {
window.location = redirectUrl;
}
onGeoSuccess(...);
setTimeout(redirect, 15000);
Two problems:
1) The redirect URL is being set by a function which, at least from the code you posted, is not being called
2) Even if it was called, redirectUrl
is a local variable to that function, so the timeout cannot access it.
Always check the error console.