Reputation: 331
This seems like an incredibly simple issue but I have no idea why I'm getting undefined. I'm using jQuery to fetch data off a PHP script - specifically a string which the PHP file echoes. Here's the code:
<script type="text/javascript">
var map1;
$.get("script.php", function(data)
{
map1 = data;
});
alert(map1);
</script>
Now if I alert(map1), it ends up being undefined... why exactly is this the case? I thought by declaring map1 outside $.get, it would fix the problem but that's not the case. If I alert(map1) inside the $.get function, it ends up fine and the variable holds a string (as opposed to being undefined). So the question is... what's going on with map1? And how can I stop it from being undefined / going out of scope / whatever is happening to it?
Thanks in advance.
Upvotes: 1
Views: 155
Reputation: 10713
What about doing it this way?
var map1;
$.ajax({
type: "GET",
url: "script.php",
async: true,
success : function(data)
{
map1 = data;
alert (data);
}
});
Upvotes: 1
Reputation: 48537
As @Michael has put, the .get
call is asynchronous so your javascript is executing this call, and then carrying on with your script, which is why you get an undefined
alert box.
Your best option is to put in a success
call:
$.get("script.php", function(data)
{
map1 = data;
})
.success(function() { alert(map1); });
Upvotes: 3
Reputation: 5231
$.get
runs asynchronously, and this is why the function's second parameter is an anonymous function. This anonymous function is invoked once $.get
has finished executing. alert(map1)
is invoked immediately, and not asynchronously. You could add the alert
call to the anonymous function passed to $.get
:
$.get("script.php", function(data){
map1 = data;
alert(map1);
});
Upvotes: 2
Reputation: 7536
Because your $.get
fills the data slower than your alert is executed !
Which means your $.get
function takes longer to compute than your alert !
You could use setTimeout()
to work around this but I think its a bad practice.
Upvotes: 1
Reputation: 143051
Because your alert
is executed before get
finished. Put right after assignment in function body. get
initiates the request and returns.
Upvotes: 4