How to use variable in another file?

23
May 19, 2019, at 1:50 PM

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.)

Answer 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);
}
Answer 2

remove the two var inside the displayLocation function

READ ALSO
How do I access a particular part of an HTML tag?

How do I access a particular part of an HTML tag?

I am using console on google chrome to edit the web pageI could just use inspect element and change what I am trying to change, but after discovering I could do this on the console

18
How to use an array to query

How to use an array to query

Is there any way I can use the array from $query and use it in another query like the $query2 below? It works but it only returns the first data of the array

39
MySQL query with COUNT and ORDER BY and hidden results

MySQL query with COUNT and ORDER BY and hidden results

Im trying to get a query correct where I can display the data by State with each of the States cities with stores in it with the COUNT (Number of stores in each city)Any help is greatly appreciated

36