0

I want to pass an variable to another file. I use the lat variable in new js file but not working.

In address.php:

<div class="saveaddress">Click me</div>

<script>
    var lat;
    var lng;
    function displayLocation(position) {
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;
    } 
</script>
.
.
.
<script src="js/save.js"></script>

save.js file:

$('.saveaddress').click(function(){
    alert(lat);
}

How can I do that? (How can I do that? (I followed other questions but not worked for me.)

1
  • 1
    Did you try not redclaring lat and lng? Change var lat = position.coords.latitude; to lat = position.coords.latitude; and see if that works. Commented May 18, 2019 at 14:45

2 Answers 2

1

You should try fixing the scope of the variable by not redclaring:

var lat;
var lng;
function displayLocation(position) {
    lat = position.coords.latitude;
    lng = position.coords.longitude;
} 

Alternatively, you could add the variable to the window:

function displayLocation(position) {
    window.lat = position.coords.latitude;
    window.lng = position.coords.longitude;
} 

Then:

$('.saveaddress').click(function(){
    alert(window.lat);
}
Sign up to request clarification or add additional context in comments.

Comments

0

remove the two var inside the displayLocation function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.