While JavaScript is single-threaded, it can perform tasks asynchronously, i.e. function calls do not necessarily complete before the next line of code. AJAX (asynchronous JavaScript and XML) calls do just that. For example,
console.log("starting")
$.getJSON("path/to/resource", function (data) {
console.log("data retrieved")
})
console.log("finished")
The above code will most likely print starting
and finished
before it prints data retrieved
. This is because $.getJSON
is asynchronous. It requests a resource on a server somewhere, waits for a response, then calls the anonymous function provided as a callback, i.e. the function (data) { /* etc */ }
part.
In your case, the callback function is running after alert
, even though it is written above it in your code. If you want to alert(solarSystem)
, you'll need to place that inside of your $.getJSON
call to ensure it is processed correctly:
solarSystem = "test"
$.getJSON("ajax/getLocation.php", function (data) {
var items = []
$.each(data, function (key, val) {
solarSystem = val
})
alert(solarSystem)
})